From 8115b32c1f601343f9ce2d614fd008e6cfa51e9f Mon Sep 17 00:00:00 2001 From: ujijrujijr Date: Wed, 6 Mar 2024 09:21:43 +0400 Subject: [PATCH] =?UTF-8?q?=D0=97=D0=B0=D0=BB=D0=B8=D0=BB=20=D0=BB=D0=B0?= =?UTF-8?q?=D0=B1=201?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- GarmentFactory/Form1.Designer.cs | 39 --- GarmentFactory/Form1.cs | 10 - GarmentFactory/FormComponent.Designer.cs | 118 +++++++++ GarmentFactory/FormComponent.cs | 88 +++++++ GarmentFactory/FormComponent.resx | 120 +++++++++ GarmentFactory/FormComponents.Designer.cs | 117 +++++++++ GarmentFactory/FormComponents.cs | 112 ++++++++ GarmentFactory/FormComponents.resx | 120 +++++++++ GarmentFactory/FormCreateOrder.Designer.cs | 147 +++++++++++ GarmentFactory/FormCreateOrder.cs | 124 +++++++++ GarmentFactory/FormCreateOrder.resx | 120 +++++++++ GarmentFactory/FormMain.Designer.cs | 183 +++++++++++++ GarmentFactory/FormMain.cs | 152 +++++++++++ GarmentFactory/FormMain.resx | 123 +++++++++ GarmentFactory/FormTextile.Designer.cs | 241 ++++++++++++++++++ GarmentFactory/FormTextile.cs | 217 ++++++++++++++++ GarmentFactory/FormTextile.resx | 129 ++++++++++ .../FormTextileComponent.Designer.cs | 118 +++++++++ GarmentFactory/FormTextileComponent.cs | 90 +++++++ GarmentFactory/FormTextileComponent.resx | 120 +++++++++ GarmentFactory/FormTextiles.Designer.cs | 115 +++++++++ GarmentFactory/FormTextiles.cs | 111 ++++++++ GarmentFactory/FormTextiles.resx | 120 +++++++++ GarmentFactory/GarmentFactory.csproj | 11 - GarmentFactory/GarmentFactory.sln | 26 +- GarmentFactory/GarmentFactoryView.csproj | 35 +++ GarmentFactory/Program.cs | 38 ++- .../Properties/Resources.Designer.cs | 63 +++++ .../{Form1.resx => Properties/Resources.resx} | 0 GarmentFactory/Properties/launchSettings.json | 7 + GarmentFactoryBusinessLogic/ComponentLogic.cs | 117 +++++++++ .../GarmentFactoryBusinessLogic.csproj | 18 ++ GarmentFactoryBusinessLogic/OrderLogic.cs | 139 ++++++++++ GarmentFactoryBusinessLogic/TextileLogic.cs | 126 +++++++++ .../BindingModels/ComponentBindingModel.cs | 16 ++ .../BindingModels/OrderBindingModel.cs | 21 ++ .../BindingModels/TextileBindingModel.cs | 17 ++ .../IComponentLogic.cs | 21 ++ .../BusinessLogicsContracts/IOrderLogic.cs | 20 ++ .../BusinessLogicsContracts/ITextileLogic.cs | 20 ++ .../GarmentFactoryContracts.csproj | 17 ++ .../SearchModels/ComponentSearchModel.cs | 14 + .../SearchModels/OrderSearchModel.cs | 13 + .../SearchModels/TextileSearchModel.cs | 14 + .../StoragesContracts/IComponentStorage.cs | 21 ++ .../StoragesContracts/IOrderStorage.cs | 21 ++ .../StoragesContracts/ITextileStorage.cs | 21 ++ .../ViewModels/ComponentViewModel.cs | 21 ++ .../ViewModels/OrderViewModel.cs | 37 +++ .../ViewModels/TextileViewModel.cs | 20 ++ GarmentFactoryDataModels/Enums/OrderStatus.cs | 11 + .../GarmentFactoryDataModels.csproj | 13 + GarmentFactoryDataModels/IId.cs | 13 + .../Models/IComponentModel.cs | 14 + .../Models/IOrderModel.cs | 19 ++ .../Models/ITextileModel.cs | 15 ++ .../DataListSingleton.cs | 26 ++ .../GarmentFactoryListImplement.csproj | 18 ++ .../Implements/ComponentStorage.cs | 106 ++++++++ .../Implements/OrderStorage.cs | 137 ++++++++++ .../Implements/TextileStorage.cs | 121 +++++++++ .../Models/Component.cs | 46 ++++ GarmentFactoryListImplement/Models/Order.cs | 65 +++++ GarmentFactoryListImplement/Models/Textile.cs | 50 ++++ 64 files changed, 4320 insertions(+), 62 deletions(-) delete mode 100644 GarmentFactory/Form1.Designer.cs delete mode 100644 GarmentFactory/Form1.cs create mode 100644 GarmentFactory/FormComponent.Designer.cs create mode 100644 GarmentFactory/FormComponent.cs create mode 100644 GarmentFactory/FormComponent.resx create mode 100644 GarmentFactory/FormComponents.Designer.cs create mode 100644 GarmentFactory/FormComponents.cs create mode 100644 GarmentFactory/FormComponents.resx create mode 100644 GarmentFactory/FormCreateOrder.Designer.cs create mode 100644 GarmentFactory/FormCreateOrder.cs create mode 100644 GarmentFactory/FormCreateOrder.resx create mode 100644 GarmentFactory/FormMain.Designer.cs create mode 100644 GarmentFactory/FormMain.cs create mode 100644 GarmentFactory/FormMain.resx create mode 100644 GarmentFactory/FormTextile.Designer.cs create mode 100644 GarmentFactory/FormTextile.cs create mode 100644 GarmentFactory/FormTextile.resx create mode 100644 GarmentFactory/FormTextileComponent.Designer.cs create mode 100644 GarmentFactory/FormTextileComponent.cs create mode 100644 GarmentFactory/FormTextileComponent.resx create mode 100644 GarmentFactory/FormTextiles.Designer.cs create mode 100644 GarmentFactory/FormTextiles.cs create mode 100644 GarmentFactory/FormTextiles.resx delete mode 100644 GarmentFactory/GarmentFactory.csproj create mode 100644 GarmentFactory/GarmentFactoryView.csproj create mode 100644 GarmentFactory/Properties/Resources.Designer.cs rename GarmentFactory/{Form1.resx => Properties/Resources.resx} (100%) create mode 100644 GarmentFactory/Properties/launchSettings.json create mode 100644 GarmentFactoryBusinessLogic/ComponentLogic.cs create mode 100644 GarmentFactoryBusinessLogic/GarmentFactoryBusinessLogic.csproj create mode 100644 GarmentFactoryBusinessLogic/OrderLogic.cs create mode 100644 GarmentFactoryBusinessLogic/TextileLogic.cs create mode 100644 GarmentFactoryContracts/BindingModels/ComponentBindingModel.cs create mode 100644 GarmentFactoryContracts/BindingModels/OrderBindingModel.cs create mode 100644 GarmentFactoryContracts/BindingModels/TextileBindingModel.cs create mode 100644 GarmentFactoryContracts/BusinessLogicsContracts/IComponentLogic.cs create mode 100644 GarmentFactoryContracts/BusinessLogicsContracts/IOrderLogic.cs create mode 100644 GarmentFactoryContracts/BusinessLogicsContracts/ITextileLogic.cs create mode 100644 GarmentFactoryContracts/GarmentFactoryContracts.csproj create mode 100644 GarmentFactoryContracts/SearchModels/ComponentSearchModel.cs create mode 100644 GarmentFactoryContracts/SearchModels/OrderSearchModel.cs create mode 100644 GarmentFactoryContracts/SearchModels/TextileSearchModel.cs create mode 100644 GarmentFactoryContracts/StoragesContracts/IComponentStorage.cs create mode 100644 GarmentFactoryContracts/StoragesContracts/IOrderStorage.cs create mode 100644 GarmentFactoryContracts/StoragesContracts/ITextileStorage.cs create mode 100644 GarmentFactoryContracts/ViewModels/ComponentViewModel.cs create mode 100644 GarmentFactoryContracts/ViewModels/OrderViewModel.cs create mode 100644 GarmentFactoryContracts/ViewModels/TextileViewModel.cs create mode 100644 GarmentFactoryDataModels/Enums/OrderStatus.cs create mode 100644 GarmentFactoryDataModels/GarmentFactoryDataModels.csproj create mode 100644 GarmentFactoryDataModels/IId.cs create mode 100644 GarmentFactoryDataModels/Models/IComponentModel.cs create mode 100644 GarmentFactoryDataModels/Models/IOrderModel.cs create mode 100644 GarmentFactoryDataModels/Models/ITextileModel.cs create mode 100644 GarmentFactoryListImplement/DataListSingleton.cs create mode 100644 GarmentFactoryListImplement/GarmentFactoryListImplement.csproj create mode 100644 GarmentFactoryListImplement/Implements/ComponentStorage.cs create mode 100644 GarmentFactoryListImplement/Implements/OrderStorage.cs create mode 100644 GarmentFactoryListImplement/Implements/TextileStorage.cs create mode 100644 GarmentFactoryListImplement/Models/Component.cs create mode 100644 GarmentFactoryListImplement/Models/Order.cs create mode 100644 GarmentFactoryListImplement/Models/Textile.cs diff --git a/GarmentFactory/Form1.Designer.cs b/GarmentFactory/Form1.Designer.cs deleted file mode 100644 index 1ef0e0c..0000000 --- a/GarmentFactory/Form1.Designer.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace GarmentFactory -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.components = new System.ComponentModel.Container(); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(800, 450); - this.Text = "Form1"; - } - - #endregion - } -} \ No newline at end of file diff --git a/GarmentFactory/Form1.cs b/GarmentFactory/Form1.cs deleted file mode 100644 index a73c48a..0000000 --- a/GarmentFactory/Form1.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace GarmentFactory -{ - public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - } -} \ No newline at end of file diff --git a/GarmentFactory/FormComponent.Designer.cs b/GarmentFactory/FormComponent.Designer.cs new file mode 100644 index 0000000..3170fe1 --- /dev/null +++ b/GarmentFactory/FormComponent.Designer.cs @@ -0,0 +1,118 @@ +namespace GarmentFactoryView +{ + partial class FormComponent + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + labelName = new Label(); + labelCost = new Label(); + textBoxName = new TextBox(); + textBoxCost = new TextBox(); + buttonSave = new Button(); + button2 = new Button(); + SuspendLayout(); + // + // labelName + // + labelName.AutoSize = true; + labelName.Location = new Point(12, 34); + labelName.Name = "labelName"; + labelName.Size = new Size(80, 20); + labelName.TabIndex = 0; + labelName.Text = "Название:"; + // + // labelCost + // + labelCost.AutoSize = true; + labelCost.Location = new Point(12, 85); + labelCost.Name = "labelCost"; + labelCost.Size = new Size(48, 20); + labelCost.TabIndex = 1; + labelCost.Text = "Цена:"; + // + // textBoxName + // + textBoxName.Location = new Point(104, 31); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(215, 27); + textBoxName.TabIndex = 2; + // + // textBoxCost + // + textBoxCost.Location = new Point(104, 82); + textBoxCost.Name = "textBoxCost"; + textBoxCost.Size = new Size(125, 27); + textBoxCost.TabIndex = 3; + // + // buttonSave + // + buttonSave.Location = new Point(187, 138); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(94, 29); + buttonSave.TabIndex = 4; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // button2 + // + button2.Location = new Point(288, 138); + button2.Name = "button2"; + button2.Size = new Size(94, 29); + button2.TabIndex = 5; + button2.Text = "Отмена"; + button2.UseVisualStyleBackColor = true; + button2.Click += ButtonCancel_Click; + // + // FormComponent + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(394, 179); + Controls.Add(button2); + Controls.Add(buttonSave); + Controls.Add(textBoxCost); + Controls.Add(textBoxName); + Controls.Add(labelCost); + Controls.Add(labelName); + Name = "FormComponent"; + Text = "Компонент"; + Load += FormComponent_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelName; + private Label labelCost; + private TextBox textBoxName; + private TextBox textBoxCost; + private Button buttonSave; + private Button button2; + } +} \ No newline at end of file diff --git a/GarmentFactory/FormComponent.cs b/GarmentFactory/FormComponent.cs new file mode 100644 index 0000000..8983fcc --- /dev/null +++ b/GarmentFactory/FormComponent.cs @@ -0,0 +1,88 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using GarmentFactoryContracts.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 GarmentFactoryView +{ + public partial class FormComponent : Form + { + private readonly ILogger _logger; + private readonly IComponentLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + public FormComponent(ILogger logger, IComponentLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + private void FormComponent_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение компонента"); + var view = _logic.ReadElement(new ComponentSearchModel {Id = _id.Value}); + if (view != null) + { + textBoxName.Text = view.ComponentName; + textBoxCost.Text = view.Cost.ToString(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение компонента"); + try + { + var model = new ComponentBindingModel + { + Id = _id ?? 0, + ComponentName = textBoxName.Text, + Cost = Convert.ToDouble(textBoxCost.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, "Ошибка сохранения компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/GarmentFactory/FormComponent.resx b/GarmentFactory/FormComponent.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/GarmentFactory/FormComponent.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/GarmentFactory/FormComponents.Designer.cs b/GarmentFactory/FormComponents.Designer.cs new file mode 100644 index 0000000..173772d --- /dev/null +++ b/GarmentFactory/FormComponents.Designer.cs @@ -0,0 +1,117 @@ +namespace GarmentFactoryView +{ + partial class FormComponents + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + buttonAdd = new Button(); + buttonUpdate = new Button(); + buttonDelete = new Button(); + buttonRefresh = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Left; + dataGridView.Location = new Point(0, 0); + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(620, 450); + dataGridView.TabIndex = 0; + // + // buttonAdd + // + buttonAdd.Location = new Point(656, 48); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(120, 40); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += ButtonAdd_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(656, 113); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(120, 40); + buttonUpdate.TabIndex = 2; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += ButtonUpdate_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(656, 181); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(120, 40); + buttonDelete.TabIndex = 3; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += ButtonDelete_Click; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(656, 250); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(120, 40); + buttonRefresh.TabIndex = 4; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += ButtonRefresh_Click; + // + // FormComponents + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(buttonRefresh); + Controls.Add(buttonDelete); + Controls.Add(buttonUpdate); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Name = "FormComponents"; + Text = "Компоненты"; + Load += FormComponents_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonAdd; + private Button buttonUpdate; + private Button buttonDelete; + private Button buttonRefresh; + } +} \ No newline at end of file diff --git a/GarmentFactory/FormComponents.cs b/GarmentFactory/FormComponents.cs new file mode 100644 index 0000000..c1e9177 --- /dev/null +++ b/GarmentFactory/FormComponents.cs @@ -0,0 +1,112 @@ +using GarmentFactory; +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace GarmentFactoryView +{ + public partial class FormComponents : Form + { + private readonly ILogger _logger; + private readonly IComponentLogic _logic; + public FormComponents(ILogger logger, IComponentLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormComponents_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["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка компонентов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки компонентов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); + if (service is FormComponent form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void ButtonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); + if (service is FormComponent form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void ButtonDelete_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 ComponentBindingModel { Id = id })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonRefresh_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/GarmentFactory/FormComponents.resx b/GarmentFactory/FormComponents.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/GarmentFactory/FormComponents.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/GarmentFactory/FormCreateOrder.Designer.cs b/GarmentFactory/FormCreateOrder.Designer.cs new file mode 100644 index 0000000..a49b49d --- /dev/null +++ b/GarmentFactory/FormCreateOrder.Designer.cs @@ -0,0 +1,147 @@ +namespace GarmentFactoryView +{ + partial class FormCreateOrder + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + buttonSave = new Button(); + buttonCancel = new Button(); + labelTextile = new Label(); + labelCount = new Label(); + labelSum = new Label(); + textBoxCount = new TextBox(); + textBoxSum = new TextBox(); + comboBoxTextile = new ComboBox(); + SuspendLayout(); + // + // buttonSave + // + buttonSave.Location = new Point(238, 168); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(94, 29); + buttonSave.TabIndex = 0; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(347, 168); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(94, 29); + buttonCancel.TabIndex = 1; + buttonCancel.Text = "Отменить"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // labelTextile + // + labelTextile.AutoSize = true; + labelTextile.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point); + labelTextile.Location = new Point(35, 24); + labelTextile.Name = "labelTextile"; + labelTextile.Size = new Size(71, 20); + labelTextile.TabIndex = 2; + labelTextile.Text = "Текстиль:"; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point); + labelCount.Location = new Point(35, 67); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(93, 20); + labelCount.TabIndex = 3; + labelCount.Text = "Количество:"; + // + // labelSum + // + labelSum.AutoSize = true; + labelSum.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point); + labelSum.Location = new Point(35, 111); + labelSum.Name = "labelSum"; + labelSum.Size = new Size(58, 20); + labelSum.TabIndex = 4; + labelSum.Text = "Сумма:"; + // + // textBoxCount + // + textBoxCount.Location = new Point(134, 67); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(247, 27); + textBoxCount.TabIndex = 5; + textBoxCount.TextChanged += TextBoxCount_TextChanged; + // + // textBoxSum + // + textBoxSum.Enabled = false; + textBoxSum.Location = new Point(134, 111); + textBoxSum.Name = "textBoxSum"; + textBoxSum.Size = new Size(247, 27); + textBoxSum.TabIndex = 6; + // + // comboBoxTextile + // + comboBoxTextile.FormattingEnabled = true; + comboBoxTextile.Location = new Point(134, 24); + comboBoxTextile.Name = "comboBoxTextile"; + comboBoxTextile.Size = new Size(247, 28); + comboBoxTextile.TabIndex = 7; + comboBoxTextile.SelectedIndexChanged += ComboBoxProduct_SelectedIndexChanged; + // + // FormCreateOrder + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(453, 209); + Controls.Add(comboBoxTextile); + Controls.Add(textBoxSum); + Controls.Add(textBoxCount); + Controls.Add(labelSum); + Controls.Add(labelCount); + Controls.Add(labelTextile); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Name = "FormCreateOrder"; + Text = "Заказ"; + Load += FormCreateOrder_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonSave; + private Button buttonCancel; + private Label labelTextile; + private Label labelCount; + private Label labelSum; + private TextBox textBoxCount; + private TextBox textBoxSum; + private ComboBox comboBoxTextile; + } +} \ No newline at end of file diff --git a/GarmentFactory/FormCreateOrder.cs b/GarmentFactory/FormCreateOrder.cs new file mode 100644 index 0000000..d1c7561 --- /dev/null +++ b/GarmentFactory/FormCreateOrder.cs @@ -0,0 +1,124 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using GarmentFactoryContracts.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 GarmentFactoryView +{ + public partial class FormCreateOrder : Form + { + private readonly ILogger _logger; + private readonly ITextileLogic _logicT; + private readonly IOrderLogic _logicO; + + public FormCreateOrder(ILogger logger, ITextileLogic logicT, IOrderLogic logicO) + { + InitializeComponent(); + _logger = logger; + _logicT = logicT; + _logicO = logicO; + } + private void FormCreateOrder_Load(object sender, EventArgs e) + { + _logger.LogInformation("Загрузка текстилей для заказа"); + try + { + var textileList = _logicT.ReadList(null); + if (textileList != null) + { + comboBoxTextile.DisplayMember = "TextileName"; + comboBoxTextile.ValueMember = "Id"; + comboBoxTextile.DataSource = textileList; + comboBoxTextile.SelectedItem = null; + _logger.LogInformation("Загрузка текстиля для заказа"); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка во время загрузки текстиля для заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + //Суммарная стоимость чека + private void CalcSum() + { + if (comboBoxTextile.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text)) + { + try + { + int id = Convert.ToInt32(comboBoxTextile.SelectedValue); + var textile = _logicT.ReadElement(new TextileSearchModel { Id = id }); + int count = Convert.ToInt32(textBoxCount.Text); + textBoxSum.Text = Math.Round(count * (textile?.Price ?? 0), 2).ToString(); + _logger.LogInformation("Расчет суммы заказа"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка расчета суммы заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void TextBoxCount_TextChanged(object sender, EventArgs e) + { + CalcSum(); + } + + private void ComboBoxProduct_SelectedIndexChanged(object sender, EventArgs e) + { + CalcSum(); + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxTextile.SelectedValue == null) + { + MessageBox.Show("Выберите текстиль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Создание заказа"); + try + { + var operationResult = _logicO.CreateOrder(new OrderBindingModel + { + TextileId = Convert.ToInt32(comboBoxTextile.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text), + Sum = Convert.ToDouble(textBoxSum.Text) + }); + if (!operationResult) + { + throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка создания заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/GarmentFactory/FormCreateOrder.resx b/GarmentFactory/FormCreateOrder.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/GarmentFactory/FormCreateOrder.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/GarmentFactory/FormMain.Designer.cs b/GarmentFactory/FormMain.Designer.cs new file mode 100644 index 0000000..7b3dbfb --- /dev/null +++ b/GarmentFactory/FormMain.Designer.cs @@ -0,0 +1,183 @@ +namespace GarmentFactoryView +{ + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + buttonCreateOrder = new Button(); + buttonTakeOrderInWork = new Button(); + buttonOrderReady = new Button(); + buttonCompletedOrder = new Button(); + buttonRefresh = new Button(); + menuStrip1 = new MenuStrip(); + справочникиToolStripMenuItem = new ToolStripMenuItem(); + компонентыToolStripMenuItem = new ToolStripMenuItem(); + текстилиToolStripMenuItem = new ToolStripMenuItem(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + menuStrip1.SuspendLayout(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(0, 31); + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(950, 425); + dataGridView.TabIndex = 0; + // + // buttonCreateOrder + // + buttonCreateOrder.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point); + buttonCreateOrder.Location = new Point(977, 80); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(180, 40); + buttonCreateOrder.TabIndex = 1; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // buttonTakeOrderInWork + // + buttonTakeOrderInWork.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point); + buttonTakeOrderInWork.Location = new Point(977, 147); + buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; + buttonTakeOrderInWork.Size = new Size(180, 40); + buttonTakeOrderInWork.TabIndex = 2; + buttonTakeOrderInWork.Text = "Отдать на выполнение"; + buttonTakeOrderInWork.UseVisualStyleBackColor = true; + buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; + // + // buttonOrderReady + // + buttonOrderReady.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point); + buttonOrderReady.Location = new Point(977, 217); + buttonOrderReady.Name = "buttonOrderReady"; + buttonOrderReady.Size = new Size(180, 40); + buttonOrderReady.TabIndex = 3; + buttonOrderReady.Text = "Заказ готов"; + buttonOrderReady.UseVisualStyleBackColor = true; + buttonOrderReady.Click += ButtonOrderReady_Click; + // + // buttonCompletedOrder + // + buttonCompletedOrder.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point); + buttonCompletedOrder.Location = new Point(977, 285); + buttonCompletedOrder.Name = "buttonCompletedOrder"; + buttonCompletedOrder.Size = new Size(180, 40); + buttonCompletedOrder.TabIndex = 4; + buttonCompletedOrder.Text = "Заказ выдан"; + buttonCompletedOrder.UseVisualStyleBackColor = true; + buttonCompletedOrder.Click += ButtonCompletedOrder_Click; + // + // buttonRefresh + // + buttonRefresh.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point); + buttonRefresh.Location = new Point(977, 363); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(180, 40); + buttonRefresh.TabIndex = 5; + buttonRefresh.Text = "Обновить список"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += ButtonRefresh_Click; + // + // menuStrip1 + // + menuStrip1.ImageScalingSize = new Size(20, 20); + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Size = new Size(1169, 28); + menuStrip1.TabIndex = 7; + menuStrip1.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компоненты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; + // + // FormMain + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1169, 453); + Controls.Add(menuStrip1); + Controls.Add(buttonRefresh); + Controls.Add(buttonCompletedOrder); + Controls.Add(buttonOrderReady); + Controls.Add(buttonTakeOrderInWork); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + MainMenuStrip = menuStrip1; + Name = "FormMain"; + Text = "Швейная фабрика"; + Load += FormMain_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonCreateOrder; + private Button buttonTakeOrderInWork; + private Button buttonOrderReady; + private Button buttonCompletedOrder; + private Button buttonRefresh; + private MenuStrip menuStrip1; + private ToolStripMenuItem справочникиToolStripMenuItem; + private ToolStripMenuItem компонентыToolStripMenuItem; + private ToolStripMenuItem текстилиToolStripMenuItem; + } +} \ No newline at end of file diff --git a/GarmentFactory/FormMain.cs b/GarmentFactory/FormMain.cs new file mode 100644 index 0000000..b921a1c --- /dev/null +++ b/GarmentFactory/FormMain.cs @@ -0,0 +1,152 @@ +using GarmentFactory; +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace GarmentFactoryView +{ + public partial class FormMain : Form + { + private readonly ILogger _logger; + private readonly IOrderLogic _orderLogic; + public FormMain(ILogger logger, IOrderLogic orderLogic) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + } + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); + try + { + var list = _orderLogic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["TextileId"].Visible = false; + dataGridView.Columns["TextileName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } + + 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(FormTextiles)); + if (service is FormTextiles 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 ButtonCompletedOrder_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 ButtonRefresh_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/GarmentFactory/FormMain.resx b/GarmentFactory/FormMain.resx new file mode 100644 index 0000000..4f2836b --- /dev/null +++ b/GarmentFactory/FormMain.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 143, 17 + + \ No newline at end of file diff --git a/GarmentFactory/FormTextile.Designer.cs b/GarmentFactory/FormTextile.Designer.cs new file mode 100644 index 0000000..5121014 --- /dev/null +++ b/GarmentFactory/FormTextile.Designer.cs @@ -0,0 +1,241 @@ +namespace GarmentFactoryView +{ + partial class FormTextile + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + label1 = new Label(); + label2 = new Label(); + textBoxName = new TextBox(); + textBoxPrice = new TextBox(); + groupBoxTextileComponents = new GroupBox(); + buttonRefresh = new Button(); + buttonDelete = new Button(); + buttonUpdate = new Button(); + buttonAdd = new Button(); + dataGridView = new DataGridView(); + Column1 = new DataGridViewTextBoxColumn(); + Column2 = new DataGridViewTextBoxColumn(); + Column3 = new DataGridViewTextBoxColumn(); + buttonSave = new Button(); + buttonCancel = new Button(); + groupBoxTextileComponents.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(12, 21); + label1.Name = "label1"; + label1.Size = new Size(80, 20); + label1.TabIndex = 0; + label1.Text = "Название:"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(12, 63); + label2.Name = "label2"; + label2.Size = new Size(86, 20); + label2.TabIndex = 1; + label2.Text = "Стоимость:"; + // + // textBoxName + // + textBoxName.Location = new Point(110, 21); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(358, 27); + textBoxName.TabIndex = 2; + // + // textBoxPrice + // + textBoxPrice.Enabled = false; + textBoxPrice.Location = new Point(110, 63); + textBoxPrice.Name = "textBoxPrice"; + textBoxPrice.Size = new Size(209, 27); + textBoxPrice.TabIndex = 3; + // + // groupBoxTextileComponents + // + groupBoxTextileComponents.Controls.Add(buttonRefresh); + groupBoxTextileComponents.Controls.Add(buttonDelete); + groupBoxTextileComponents.Controls.Add(buttonUpdate); + groupBoxTextileComponents.Controls.Add(buttonAdd); + groupBoxTextileComponents.Controls.Add(dataGridView); + groupBoxTextileComponents.Location = new Point(12, 115); + groupBoxTextileComponents.Name = "groupBoxTextileComponents"; + groupBoxTextileComponents.Size = new Size(776, 323); + groupBoxTextileComponents.TabIndex = 5; + groupBoxTextileComponents.TabStop = false; + groupBoxTextileComponents.Text = "Компоненты"; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(623, 254); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(120, 40); + buttonRefresh.TabIndex = 4; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += ButtonRefresh_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(623, 174); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(120, 40); + buttonDelete.TabIndex = 3; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += ButtonDelete_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(623, 97); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(120, 40); + buttonUpdate.TabIndex = 2; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += ButtonUpdate_Click; + // + // buttonAdd + // + buttonAdd.Location = new Point(623, 26); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(120, 40); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += ButtonAdd_Click; + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { Column1, Column2, Column3 }); + dataGridView.Dock = DockStyle.Left; + dataGridView.Location = new Point(3, 23); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(574, 297); + dataGridView.TabIndex = 0; + // + // Column1 + // + Column1.HeaderText = "Id"; + Column1.MinimumWidth = 6; + Column1.Name = "Column1"; + Column1.ReadOnly = true; + Column1.Visible = false; + Column1.Width = 125; + // + // Column2 + // + Column2.HeaderText = "Компонент"; + Column2.MinimumWidth = 6; + Column2.Name = "Column2"; + Column2.ReadOnly = true; + Column2.Width = 125; + // + // Column3 + // + Column3.HeaderText = "Количество"; + Column3.MinimumWidth = 6; + Column3.Name = "Column3"; + Column3.ReadOnly = true; + Column3.Width = 125; + // + // buttonSave + // + buttonSave.Font = new Font("Segoe UI", 9F, FontStyle.Bold, GraphicsUnit.Point); + buttonSave.Location = new Point(547, 472); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(103, 40); + buttonSave.TabIndex = 6; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // buttonCancel + // + buttonCancel.Font = new Font("Segoe UI", 9F, FontStyle.Bold, GraphicsUnit.Point); + buttonCancel.Location = new Point(665, 472); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(103, 40); + buttonCancel.TabIndex = 7; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // FormTextile + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 545); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(groupBoxTextileComponents); + Controls.Add(textBoxPrice); + Controls.Add(textBoxName); + Controls.Add(label2); + Controls.Add(label1); + Name = "FormTextile"; + Text = "Текстиль"; + Load += FormTextile_Load; + groupBoxTextileComponents.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label label1; + private Label label2; + private TextBox textBoxName; + private TextBox textBoxPrice; + private GroupBox groupBoxTextileComponents; + private Button buttonRefresh; + private Button buttonDelete; + private Button buttonUpdate; + private Button buttonAdd; + private DataGridView dataGridView; + private Button buttonSave; + private Button buttonCancel; + private DataGridViewTextBoxColumn Column1; + private DataGridViewTextBoxColumn Column2; + private DataGridViewTextBoxColumn Column3; + } +} \ No newline at end of file diff --git a/GarmentFactory/FormTextile.cs b/GarmentFactory/FormTextile.cs new file mode 100644 index 0000000..280ec62 --- /dev/null +++ b/GarmentFactory/FormTextile.cs @@ -0,0 +1,217 @@ +using GarmentFactory; +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryDataModels.Models; +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 GarmentFactoryView +{ + public partial class FormTextile : Form + { + private readonly ILogger _logger; + private readonly ITextileLogic _logic; + private int? _id; + private Dictionary _textileComponents; + public int Id { set { _id = value; } } + + public FormTextile(ILogger logger, ITextileLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + _textileComponents = new Dictionary(); + } + + //Загрузка данных в таблицу + private void LoadData() + { + _logger.LogInformation("Загрузка компонента текстиля"); + try + { + var list = _logic.ReadList(null); + if (_textileComponents != null) + { + dataGridView.Rows.Clear(); + foreach (var textileC in _textileComponents) + { + dataGridView.Rows.Add(new object[] { textileC.Key, textileC.Value.Item1.ComponentName, textileC.Value.Item2 }); + } + textBoxPrice.Text = CalcPrice().ToString(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки компонента текстиля"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void FormTextile_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Загрузка текстиля"); + try + { + var view = _logic.ReadElement(new TextileSearchModel { Id = _id.Value }); + if (view != null) + { + textBoxName.Text = view.TextileName; + textBoxPrice.Text = view.Price.ToString(); + _textileComponents = view.TextileComponents ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки текстиля"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void ButtonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormTextileComponent)); + if (service is FormTextileComponent form) + { + if (form.ShowDialog() == DialogResult.OK) + { + if (form.ComponentModel == null) + { + return; + } + _logger.LogInformation("Добавление нового компонента: {ComponentName} - {Count}", form.ComponentModel.ComponentName, form.Count); + if (_textileComponents.ContainsKey(form.Id)) + { + _textileComponents[form.Id] = (form.ComponentModel, form.Count); + } + else + { + _textileComponents.Add(form.Id, (form.ComponentModel, form.Count)); + } + LoadData(); + } + } + } + + private void ButtonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormTextileComponent)); + if (service is FormTextileComponent form) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); + form.Id = id; + form.Count = _textileComponents[id].Item2; + if (form.ShowDialog() == DialogResult.OK) + { + if (form.ComponentModel == null) + { + return; + } + _logger.LogInformation("Изменение компонента: {ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); + _textileComponents[form.Id] = (form.ComponentModel, form.Count); + LoadData(); + } + } + } + } + + private void ButtonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + try + { + _logger.LogInformation("Удаление компонента: {ComponentName} - {Count}", dataGridView.SelectedRows[0].Cells[1].Value); + _textileComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + LoadData(); + } + } + } + private void ButtonRefresh_Click(object sender, EventArgs e) + { + LoadData(); + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxPrice.Text)) + { + MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (_textileComponents == null || _textileComponents.Count == 0) + { + MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение текстиля"); + try + { + var model = new TextileBindingModel + { + Id = _id ?? 0, + TextileName = textBoxName.Text, + Price = Convert.ToDouble(textBoxPrice.Text), + TextileComponents = _textileComponents + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения текстиля"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + //Вычисление стоимости товара по его компонентам + private double CalcPrice() + { + double price = 0; + foreach (var elem in _textileComponents) + { + price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2); + } + return Math.Round(price * 1.1, 2); + } + + } +} diff --git a/GarmentFactory/FormTextile.resx b/GarmentFactory/FormTextile.resx new file mode 100644 index 0000000..dbdd69b --- /dev/null +++ b/GarmentFactory/FormTextile.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + True + + + True + + \ No newline at end of file diff --git a/GarmentFactory/FormTextileComponent.Designer.cs b/GarmentFactory/FormTextileComponent.Designer.cs new file mode 100644 index 0000000..9e5bfaf --- /dev/null +++ b/GarmentFactory/FormTextileComponent.Designer.cs @@ -0,0 +1,118 @@ +namespace GarmentFactoryView +{ + partial class FormTextileComponent + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + labelComponent = new Label(); + labelCount = new Label(); + buttonSave = new Button(); + buttonCancel = new Button(); + textBoxCount = new TextBox(); + comboBoxComponent = new ComboBox(); + SuspendLayout(); + // + // labelComponent + // + labelComponent.AutoSize = true; + labelComponent.Location = new Point(23, 36); + labelComponent.Name = "labelComponent"; + labelComponent.Size = new Size(91, 20); + labelComponent.TabIndex = 0; + labelComponent.Text = "Компонент:"; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(23, 85); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(93, 20); + labelCount.TabIndex = 1; + labelCount.Text = "Количество:"; + // + // buttonSave + // + buttonSave.Location = new Point(222, 124); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(94, 29); + buttonSave.TabIndex = 2; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(322, 124); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(94, 29); + buttonCancel.TabIndex = 3; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // textBoxCount + // + textBoxCount.Location = new Point(122, 82); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(142, 27); + textBoxCount.TabIndex = 4; + // + // comboBoxComponent + // + comboBoxComponent.FormattingEnabled = true; + comboBoxComponent.Location = new Point(122, 36); + comboBoxComponent.Name = "comboBoxComponent"; + comboBoxComponent.Size = new Size(285, 28); + comboBoxComponent.TabIndex = 5; + // + // FormTextileComponent + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(428, 166); + Controls.Add(comboBoxComponent); + Controls.Add(textBoxCount); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(labelCount); + Controls.Add(labelComponent); + Name = "FormTextileComponent"; + Text = "Компонент текстиля"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelComponent; + private Label labelCount; + private Button buttonSave; + private Button buttonCancel; + private TextBox textBoxCount; + private ComboBox comboBoxComponent; + } +} \ No newline at end of file diff --git a/GarmentFactory/FormTextileComponent.cs b/GarmentFactory/FormTextileComponent.cs new file mode 100644 index 0000000..d00b6ef --- /dev/null +++ b/GarmentFactory/FormTextileComponent.cs @@ -0,0 +1,90 @@ +using GarmentFactoryContracts.BusinessLogicsContracts; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDataModels.Models; +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 GarmentFactoryView +{ + public partial class FormTextileComponent : Form + { + private readonly List? _list; + public int Id + { + get + { + return Convert.ToInt32(comboBoxComponent.SelectedValue); + } + set + { + comboBoxComponent.SelectedValue = value; + } + } + public IComponentModel? ComponentModel + { + get + { + if (_list == null) + { + return null; + } + foreach (var elem in _list) + { + if (elem.Id == Id) + { + return elem; + } + } + return null; + } + } + public int Count + { + get { return Convert.ToInt32(textBoxCount.Text); } + set { textBoxCount.Text = value.ToString(); } + } + + public FormTextileComponent(IComponentLogic logic) + { + InitializeComponent(); + + _list = logic.ReadList(null); + if (_list != null) + { + comboBoxComponent.DisplayMember = "ComponentName"; + comboBoxComponent.ValueMember = "Id"; + comboBoxComponent.DataSource = _list; + comboBoxComponent.SelectedItem = null; + } + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxComponent.SelectedValue == null) + { + MessageBox.Show("Выберите компонент", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + DialogResult = DialogResult.OK; + Close(); + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/GarmentFactory/FormTextileComponent.resx b/GarmentFactory/FormTextileComponent.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/GarmentFactory/FormTextileComponent.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/GarmentFactory/FormTextiles.Designer.cs b/GarmentFactory/FormTextiles.Designer.cs new file mode 100644 index 0000000..6b41417 --- /dev/null +++ b/GarmentFactory/FormTextiles.Designer.cs @@ -0,0 +1,115 @@ +namespace GarmentFactoryView +{ + partial class FormTextiles + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + buttonRefresh = new Button(); + buttonDelete = new Button(); + buttonUpdate = new Button(); + buttonAdd = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Left; + dataGridView.Location = new Point(0, 0); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(620, 450); + dataGridView.TabIndex = 0; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(654, 254); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(120, 40); + buttonRefresh.TabIndex = 8; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += ButtonRefresh_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(654, 185); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(120, 40); + buttonDelete.TabIndex = 7; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += ButtonDelete_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(654, 117); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(120, 40); + buttonUpdate.TabIndex = 6; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += ButtonUpdate_Click; + // + // buttonAdd + // + buttonAdd.Location = new Point(654, 52); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(120, 40); + buttonAdd.TabIndex = 5; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += ButtonAdd_Click; + // + // FormTextiles + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(buttonRefresh); + Controls.Add(buttonDelete); + Controls.Add(buttonUpdate); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Name = "FormTextiles"; + Text = "Текстили"; + Load += FormTextiles_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonRefresh; + private Button buttonDelete; + private Button buttonUpdate; + private Button buttonAdd; + } +} \ No newline at end of file diff --git a/GarmentFactory/FormTextiles.cs b/GarmentFactory/FormTextiles.cs new file mode 100644 index 0000000..1351baa --- /dev/null +++ b/GarmentFactory/FormTextiles.cs @@ -0,0 +1,111 @@ +using Microsoft.Extensions.Logging; +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Microsoft.VisualBasic.Logging; +using GarmentFactory; + +namespace GarmentFactoryView +{ + public partial class FormTextiles : Form + { + private readonly ILogger _logger; + + private readonly ITextileLogic _logic; + + public FormTextiles(ILogger logger, ITextileLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + // Получение всех изделий при добавлении/обновлении/удалении + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["TextileName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["TextileComponents"].Visible = false; + } + _logger.LogInformation("Загрузка текстилей"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки текстилей"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void FormTextiles_Load(object sender, EventArgs e) + { + LoadData(); + } + private void ButtonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormTextile)); + if (service is FormTextile form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + private void ButtonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormTextile)); + if (service is FormTextile form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + private void ButtonDelete_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 TextileBindingModel { Id = id })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления текстиля"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + private void ButtonRefresh_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/GarmentFactory/FormTextiles.resx b/GarmentFactory/FormTextiles.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/GarmentFactory/FormTextiles.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/GarmentFactory/GarmentFactory.csproj b/GarmentFactory/GarmentFactory.csproj deleted file mode 100644 index b57c89e..0000000 --- a/GarmentFactory/GarmentFactory.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - WinExe - net6.0-windows - enable - true - enable - - - \ No newline at end of file diff --git a/GarmentFactory/GarmentFactory.sln b/GarmentFactory/GarmentFactory.sln index c7fbbf1..acceabb 100644 --- a/GarmentFactory/GarmentFactory.sln +++ b/GarmentFactory/GarmentFactory.sln @@ -3,7 +3,15 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.7.34024.191 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GarmentFactory", "GarmentFactory.csproj", "{B47623E0-C32E-437D-869B-71BBC6994D83}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GarmentFactoryView", "GarmentFactoryView.csproj", "{B47623E0-C32E-437D-869B-71BBC6994D83}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GarmentFactoryDataModels", "..\GarmentFactoryDataModels\GarmentFactoryDataModels.csproj", "{1B91BCBE-E608-4D05-A14D-51B1765D5203}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GarmentFactoryContracts", "..\GarmentFactoryContracts\GarmentFactoryContracts.csproj", "{DB84150A-FB0D-4FCB-90DD-2CAC6845E1AF}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GarmentFactoryBusinessLogic", "..\GarmentFactoryBusinessLogic\GarmentFactoryBusinessLogic.csproj", "{218ABE4A-FF68-43EF-B257-09FCB727A3B7}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GarmentFactoryListImplement", "..\GarmentFactoryListImplement\GarmentFactoryListImplement.csproj", "{DEDDF6CC-7C47-4A10-A011-77395F4B7F30}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,6 +23,22 @@ Global {B47623E0-C32E-437D-869B-71BBC6994D83}.Debug|Any CPU.Build.0 = Debug|Any CPU {B47623E0-C32E-437D-869B-71BBC6994D83}.Release|Any CPU.ActiveCfg = Release|Any CPU {B47623E0-C32E-437D-869B-71BBC6994D83}.Release|Any CPU.Build.0 = Release|Any CPU + {1B91BCBE-E608-4D05-A14D-51B1765D5203}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1B91BCBE-E608-4D05-A14D-51B1765D5203}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1B91BCBE-E608-4D05-A14D-51B1765D5203}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1B91BCBE-E608-4D05-A14D-51B1765D5203}.Release|Any CPU.Build.0 = Release|Any CPU + {DB84150A-FB0D-4FCB-90DD-2CAC6845E1AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DB84150A-FB0D-4FCB-90DD-2CAC6845E1AF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DB84150A-FB0D-4FCB-90DD-2CAC6845E1AF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DB84150A-FB0D-4FCB-90DD-2CAC6845E1AF}.Release|Any CPU.Build.0 = Release|Any CPU + {218ABE4A-FF68-43EF-B257-09FCB727A3B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {218ABE4A-FF68-43EF-B257-09FCB727A3B7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {218ABE4A-FF68-43EF-B257-09FCB727A3B7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {218ABE4A-FF68-43EF-B257-09FCB727A3B7}.Release|Any CPU.Build.0 = Release|Any CPU + {DEDDF6CC-7C47-4A10-A011-77395F4B7F30}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DEDDF6CC-7C47-4A10-A011-77395F4B7F30}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DEDDF6CC-7C47-4A10-A011-77395F4B7F30}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DEDDF6CC-7C47-4A10-A011-77395F4B7F30}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/GarmentFactory/GarmentFactoryView.csproj b/GarmentFactory/GarmentFactoryView.csproj new file mode 100644 index 0000000..bb77e96 --- /dev/null +++ b/GarmentFactory/GarmentFactoryView.csproj @@ -0,0 +1,35 @@ + + + + WinExe + net6.0-windows + enable + true + enable + + + + + + + + + + + + + + True + True + Resources.resx + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + \ No newline at end of file diff --git a/GarmentFactory/Program.cs b/GarmentFactory/Program.cs index e6c20bf..2ff30d3 100644 --- a/GarmentFactory/Program.cs +++ b/GarmentFactory/Program.cs @@ -1,7 +1,19 @@ +using GarmentFactoryBusinessLogic; +using GarmentFactoryContracts.BusinessLogicsContracts; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryListImplement.Implements; +using GarmentFactoryView; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + + namespace GarmentFactory { internal static class Program { + private static ServiceProvider? _serviceProvider; + public static ServiceProvider? ServiceProvider => _serviceProvider; /// /// The main entry point for the application. /// @@ -11,7 +23,31 @@ namespace GarmentFactory // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new Form1()); + var services = new ServiceCollection(); + ConfigureServices(services); + _serviceProvider = services.BuildServiceProvider(); + Application.Run(_serviceProvider.GetRequiredService()); + } + private static void ConfigureServices(ServiceCollection services) + { + services.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/GarmentFactory/Properties/Resources.Designer.cs b/GarmentFactory/Properties/Resources.Designer.cs new file mode 100644 index 0000000..4489504 --- /dev/null +++ b/GarmentFactory/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// Этот код создан программой. +// Исполняемая версия:4.0.30319.42000 +// +// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае +// повторной генерации кода. +// +//------------------------------------------------------------------------------ + +namespace GarmentFactoryView.Properties { + using System; + + + /// + /// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д. + /// + // Этот класс создан автоматически классом StronglyTypedResourceBuilder + // с помощью такого средства, как ResGen или Visual Studio. + // Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen + // с параметром /str или перестройте свой проект VS. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GarmentFactoryView.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Перезаписывает свойство CurrentUICulture текущего потока для всех + /// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/GarmentFactory/Form1.resx b/GarmentFactory/Properties/Resources.resx similarity index 100% rename from GarmentFactory/Form1.resx rename to GarmentFactory/Properties/Resources.resx diff --git a/GarmentFactory/Properties/launchSettings.json b/GarmentFactory/Properties/launchSettings.json new file mode 100644 index 0000000..e8af5a0 --- /dev/null +++ b/GarmentFactory/Properties/launchSettings.json @@ -0,0 +1,7 @@ +{ + "profiles": { + "GarmentFactoryView": { + "commandName": "Project" + } + } +} \ No newline at end of file diff --git a/GarmentFactoryBusinessLogic/ComponentLogic.cs b/GarmentFactoryBusinessLogic/ComponentLogic.cs new file mode 100644 index 0000000..25e1d7f --- /dev/null +++ b/GarmentFactoryBusinessLogic/ComponentLogic.cs @@ -0,0 +1,117 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace GarmentFactoryBusinessLogic +{ + public class ComponentLogic : IComponentLogic + { + private readonly ILogger _logger; + //Хранение всех компонентов + private readonly IComponentStorage _componentStorage; + public ComponentLogic(ILogger logger, IComponentStorage componentStorage) + { + _logger = logger; + _componentStorage = componentStorage; + } + + //Чтение всего списка компонентов + public List? ReadList(ComponentSearchModel? model) + { + _logger.LogInformation("ReadList.ComponentName:{ComponentName} .Id:{Id}", model?.ComponentName, model?.Id); + var list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList.Count:{Count}", list.Count); + return list; + } + + //Чтение одного компонента + public ComponentViewModel? ReadElement(ComponentSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement.ComponentName:{ComponentName} .Id:{ Id}", model.ComponentName, model.Id); + var element = _componentStorage.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(ComponentBindingModel model) + { + CheckModel(model); + if (_componentStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + //Обновление данных компонента + public bool Update(ComponentBindingModel model) + { + CheckModel(model); + if (_componentStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + //Удаление компонента + public bool Delete(ComponentBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_componentStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + //Проверка данных компонента при добавлении/удалении/обновлении + private void CheckModel(ComponentBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ComponentName)) + { + throw new ArgumentNullException("Нет названия компонента", nameof(model.ComponentName)); + } + if (model.Cost <= 0) + { + throw new ArgumentException("Цена компонента должна быть больше 0", nameof(model.Cost)); + } + _logger.LogInformation("Component.ComponentName:{ComponentName} .Cost:{Cost} .Id:{Id}", model.ComponentName, model.Cost, model.Id); + var element = _componentStorage.GetElement(new ComponentSearchModel{ComponentName = model.ComponentName}); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Компонент с таким названием уже есть"); + } + } + } +} \ No newline at end of file diff --git a/GarmentFactoryBusinessLogic/GarmentFactoryBusinessLogic.csproj b/GarmentFactoryBusinessLogic/GarmentFactoryBusinessLogic.csproj new file mode 100644 index 0000000..f7ee440 --- /dev/null +++ b/GarmentFactoryBusinessLogic/GarmentFactoryBusinessLogic.csproj @@ -0,0 +1,18 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + diff --git a/GarmentFactoryBusinessLogic/OrderLogic.cs b/GarmentFactoryBusinessLogic/OrderLogic.cs new file mode 100644 index 0000000..37c087a --- /dev/null +++ b/GarmentFactoryBusinessLogic/OrderLogic.cs @@ -0,0 +1,139 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDataModels.Enums; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace GarmentFactoryBusinessLogic +{ + public class OrderLogic : IOrderLogic + { + private readonly ILogger _logger; + //Хранение всех заказов + private readonly IOrderStorage _orderStorage; + public OrderLogic(ILogger logger, IOrderStorage orderStorage) + { + _logger = logger; + _orderStorage = orderStorage; + } + + //Чтение всего списка заказов + public List? ReadList(OrderSearchModel? model) + { + _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); + var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList.Count:{Count}", list.Count); + return list; + } + + //Проверка данных заказа при добавлении + private void CheckModel(OrderBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (model.Sum <= 0) + { + throw new ArgumentException("Сумма чека должна быть больше 0", nameof(model.Sum)); + } + if (model.Count <= 0) + { + throw new ArgumentException("В чеке должен быть хотя бы 1 товар", nameof(model.Count)); + } + if (model.DateComplete.HasValue && model.DateComplete < model.DateCreate) + { + throw new ArgumentException($"Дата выдачи заказа {model.DateComplete} не может быть раньше даты его создания {model.DateCreate}"); + } + _logger.LogInformation("Order. Id: {Id}. Sum: {Sum}. TextileId: {TextileId}. TextileCount: {Count}", model.Id, model.Sum, model.TextileId, model.Count); + } + + public bool CreateOrder(OrderBindingModel model) + { + CheckModel(model); + if (model.Status != OrderStatus.Неизвестен) + { + _logger.LogWarning("Invalid order status"); + return false; + } + model.Status = OrderStatus.Принят; + if (_orderStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + + } + //Общий метод изменения статуса заказа + private bool ChangeStatus(OrderBindingModel model, OrderStatus newStatus) + { + CheckModel(model, false); + var order = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); + if (order == null) + { + throw new ArgumentNullException(nameof(order)); + } + model.DateCreate = order.DateCreate; + model.TextileId = order.TextileId; + model.DateComplete = order.DateComplete; + model.Status = order.Status; + model.Count = order.Count; + model.Sum = order.Sum; + if (newStatus - model.Status == 1) + { + model.Status = newStatus; + if (model.Status == OrderStatus.Выдан) + { + model.DateComplete = DateTime.Now; + } + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + if (order.Status + 1 != newStatus) + { + _logger.LogWarning("Change status operation failed. Incorrect new status: {newStatus}. Current status: {currStatus}", newStatus, order.Status); + return false; + } + _logger.LogWarning("Changing status operation faled: current:{Status}: required:{newStatus}.", model.Status, newStatus); + throw new ArgumentException($"Невозможно присвоить статус {newStatus} заказу с текущим статусом {model.Status}"); + } + + //Перевод заказа в состояние выполнения + public bool TakeOrderInWork(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Выполняется); + } + //Перевод заказа в состояние готовности + public bool FinishOrder(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Готов); + } + //Перевод заказа в состояние выдачи (окончательное завершение) + public bool DeliveryOrder(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Выдан); + } + } +} diff --git a/GarmentFactoryBusinessLogic/TextileLogic.cs b/GarmentFactoryBusinessLogic/TextileLogic.cs new file mode 100644 index 0000000..a5bed43 --- /dev/null +++ b/GarmentFactoryBusinessLogic/TextileLogic.cs @@ -0,0 +1,126 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryBusinessLogic +{ + public class TextileLogic : ITextileLogic + { + private readonly ILogger _logger; + //Хранение всех изделий + private readonly ITextileStorage _textileStorage; + public TextileLogic(ILogger logger, ITextileStorage textileStorage) + { + _logger = logger; + _textileStorage = textileStorage; + } + + //Чтение всего списка изделий + public List? ReadList(TextileSearchModel? model) + { + _logger.LogInformation("ReadList.TextileName:{TextileName} .Id:{Id}", model?.TextileName, model?.Id); + var list = model == null ? _textileStorage.GetFullList() : _textileStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList.Count:{Count}", list.Count); + return list; + } + + //Чтение одного изделия + public TextileViewModel? ReadElement(TextileSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement.TextileName:{TextileName} .Id:{ Id}", model.TextileName, model.Id); + var element = _textileStorage.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(TextileBindingModel model) + { + CheckModel(model); + if (_textileStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + //Обновление данных изделия + public bool Update(TextileBindingModel model) + { + CheckModel(model); + if (_textileStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + //Удаление изделия + public bool Delete(TextileBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete.Id:{Id}", model.Id); + if (_textileStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + //Проверка данных текстиля при добавлении/удалении/обновлении + private void CheckModel(TextileBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.TextileName)) + { + throw new ArgumentNullException("Нет названия текстиля", nameof(model.TextileName)); + } + if (model.Price <= 0) + { + throw new ArgumentException("Цена текстиля должна быть больше 0", nameof(model.Price)); + } + if (model.TextileComponents == null || model.TextileComponents.Count == 0) + { + throw new ArgumentNullException("Список кмопонентов не может быть пустым", nameof(model.TextileComponents)); + } + _logger.LogInformation("Textile. TextileName:{TextileName} .Price:{Price} .Id:{Id}", model.TextileName, model.Price, model.Id); + var element = _textileStorage.GetElement(new TextileSearchModel { TextileName = model.TextileName }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Текстиль с таким названием уже есть"); + } + } + } +} diff --git a/GarmentFactoryContracts/BindingModels/ComponentBindingModel.cs b/GarmentFactoryContracts/BindingModels/ComponentBindingModel.cs new file mode 100644 index 0000000..a97c2f4 --- /dev/null +++ b/GarmentFactoryContracts/BindingModels/ComponentBindingModel.cs @@ -0,0 +1,16 @@ +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.BindingModels +{ + public class ComponentBindingModel : IComponentModel + { + public int Id { get; set; } + public string ComponentName { get; set; } = string.Empty; + public double Cost { get; set; } + } +} diff --git a/GarmentFactoryContracts/BindingModels/OrderBindingModel.cs b/GarmentFactoryContracts/BindingModels/OrderBindingModel.cs new file mode 100644 index 0000000..2b32ea1 --- /dev/null +++ b/GarmentFactoryContracts/BindingModels/OrderBindingModel.cs @@ -0,0 +1,21 @@ +using GarmentFactoryDataModels.Enums; +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.BindingModels +{ + public class OrderBindingModel : IOrderModel + { + public int Id { get; set; } + public int TextileId { get; set; } + public int Count { get; set; } + public double Sum { get; set; } + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + public DateTime DateCreate { get; set; } = DateTime.Now; + public DateTime? DateComplete { get; set; } + } +} diff --git a/GarmentFactoryContracts/BindingModels/TextileBindingModel.cs b/GarmentFactoryContracts/BindingModels/TextileBindingModel.cs new file mode 100644 index 0000000..e823582 --- /dev/null +++ b/GarmentFactoryContracts/BindingModels/TextileBindingModel.cs @@ -0,0 +1,17 @@ +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.BindingModels +{ + public class TextileBindingModel : ITextileModel + { + public int Id { get; set; } + public string TextileName { get; set; } = string.Empty; + public double Price { get; set; } + public Dictionary TextileComponents { get; set; } = new(); + } +} diff --git a/GarmentFactoryContracts/BusinessLogicsContracts/IComponentLogic.cs b/GarmentFactoryContracts/BusinessLogicsContracts/IComponentLogic.cs new file mode 100644 index 0000000..1ff0c69 --- /dev/null +++ b/GarmentFactoryContracts/BusinessLogicsContracts/IComponentLogic.cs @@ -0,0 +1,21 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.BusinessLogicsContracts +{ + public interface IComponentLogic + { + List? ReadList(ComponentSearchModel? model); + ComponentViewModel? ReadElement(ComponentSearchModel model); + bool Create(ComponentBindingModel model); + bool Update(ComponentBindingModel model); + bool Delete(ComponentBindingModel model); + } + +} diff --git a/GarmentFactoryContracts/BusinessLogicsContracts/IOrderLogic.cs b/GarmentFactoryContracts/BusinessLogicsContracts/IOrderLogic.cs new file mode 100644 index 0000000..f735303 --- /dev/null +++ b/GarmentFactoryContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -0,0 +1,20 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.BusinessLogicsContracts +{ + public interface IOrderLogic + { + List? ReadList(OrderSearchModel? model); + bool CreateOrder(OrderBindingModel model); + bool TakeOrderInWork(OrderBindingModel model); + bool FinishOrder(OrderBindingModel model); + bool DeliveryOrder(OrderBindingModel model); + } +} diff --git a/GarmentFactoryContracts/BusinessLogicsContracts/ITextileLogic.cs b/GarmentFactoryContracts/BusinessLogicsContracts/ITextileLogic.cs new file mode 100644 index 0000000..0737fc6 --- /dev/null +++ b/GarmentFactoryContracts/BusinessLogicsContracts/ITextileLogic.cs @@ -0,0 +1,20 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.BusinessLogicsContracts +{ + public interface ITextileLogic + { + List? ReadList(TextileSearchModel? model); + TextileViewModel? ReadElement(TextileSearchModel model); + bool Create(TextileBindingModel model); + bool Update(TextileBindingModel model); + bool Delete(TextileBindingModel model); + } +} diff --git a/GarmentFactoryContracts/GarmentFactoryContracts.csproj b/GarmentFactoryContracts/GarmentFactoryContracts.csproj new file mode 100644 index 0000000..5afbe34 --- /dev/null +++ b/GarmentFactoryContracts/GarmentFactoryContracts.csproj @@ -0,0 +1,17 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + diff --git a/GarmentFactoryContracts/SearchModels/ComponentSearchModel.cs b/GarmentFactoryContracts/SearchModels/ComponentSearchModel.cs new file mode 100644 index 0000000..a9e769e --- /dev/null +++ b/GarmentFactoryContracts/SearchModels/ComponentSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.SearchModels +{ + public class ComponentSearchModel + { + public int? Id { get; set; } + public string? ComponentName { get; set; } + } +} diff --git a/GarmentFactoryContracts/SearchModels/OrderSearchModel.cs b/GarmentFactoryContracts/SearchModels/OrderSearchModel.cs new file mode 100644 index 0000000..6debaa3 --- /dev/null +++ b/GarmentFactoryContracts/SearchModels/OrderSearchModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.SearchModels +{ + public class OrderSearchModel + { + public int? Id { get; set; } + } +} diff --git a/GarmentFactoryContracts/SearchModels/TextileSearchModel.cs b/GarmentFactoryContracts/SearchModels/TextileSearchModel.cs new file mode 100644 index 0000000..b5a47bc --- /dev/null +++ b/GarmentFactoryContracts/SearchModels/TextileSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.SearchModels +{ + public class TextileSearchModel + { + public int? Id { get; set; } + public string? TextileName { get; set; } + } +} diff --git a/GarmentFactoryContracts/StoragesContracts/IComponentStorage.cs b/GarmentFactoryContracts/StoragesContracts/IComponentStorage.cs new file mode 100644 index 0000000..80e21ad --- /dev/null +++ b/GarmentFactoryContracts/StoragesContracts/IComponentStorage.cs @@ -0,0 +1,21 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.StoragesContracts +{ + public interface IComponentStorage + { + List GetFullList(); + List GetFilteredList(ComponentSearchModel model); + ComponentViewModel? GetElement(ComponentSearchModel model); + ComponentViewModel? Insert(ComponentBindingModel model); + ComponentViewModel? Update(ComponentBindingModel model); + ComponentViewModel? Delete(ComponentBindingModel model); + } +} diff --git a/GarmentFactoryContracts/StoragesContracts/IOrderStorage.cs b/GarmentFactoryContracts/StoragesContracts/IOrderStorage.cs new file mode 100644 index 0000000..b457527 --- /dev/null +++ b/GarmentFactoryContracts/StoragesContracts/IOrderStorage.cs @@ -0,0 +1,21 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.StoragesContracts +{ + public interface IOrderStorage + { + List GetFullList(); + List GetFilteredList(OrderSearchModel model); + OrderViewModel? GetElement(OrderSearchModel model); + OrderViewModel? Insert(OrderBindingModel model); + OrderViewModel? Update(OrderBindingModel model); + OrderViewModel? Delete(OrderBindingModel model); + } +} diff --git a/GarmentFactoryContracts/StoragesContracts/ITextileStorage.cs b/GarmentFactoryContracts/StoragesContracts/ITextileStorage.cs new file mode 100644 index 0000000..d949a70 --- /dev/null +++ b/GarmentFactoryContracts/StoragesContracts/ITextileStorage.cs @@ -0,0 +1,21 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.StoragesContracts +{ + public interface ITextileStorage + { + List GetFullList(); + List GetFilteredList(TextileSearchModel model); + TextileViewModel? GetElement(TextileSearchModel model); + TextileViewModel? Insert(TextileBindingModel model); + TextileViewModel? Update(TextileBindingModel model); + TextileViewModel? Delete(TextileBindingModel model); + } +} diff --git a/GarmentFactoryContracts/ViewModels/ComponentViewModel.cs b/GarmentFactoryContracts/ViewModels/ComponentViewModel.cs new file mode 100644 index 0000000..97dad5c --- /dev/null +++ b/GarmentFactoryContracts/ViewModels/ComponentViewModel.cs @@ -0,0 +1,21 @@ +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.ViewModels +{ + public class ComponentViewModel : IComponentModel + { + public int Id { get; set; } + + [DisplayName("Название компонента")] + public string ComponentName { get; set; } = string.Empty; + + [DisplayName("Цена")] + public double Cost { get; set; } + } +} diff --git a/GarmentFactoryContracts/ViewModels/OrderViewModel.cs b/GarmentFactoryContracts/ViewModels/OrderViewModel.cs new file mode 100644 index 0000000..8dc743f --- /dev/null +++ b/GarmentFactoryContracts/ViewModels/OrderViewModel.cs @@ -0,0 +1,37 @@ +using GarmentFactoryDataModels.Enums; +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.ViewModels +{ + public class OrderViewModel : IOrderModel + { + [DisplayName("Номер")] + public int Id { get; set; } + + public int TextileId { get; set; } + + [DisplayName("Текстиль")] + public string TextileName { get; set; } = string.Empty; + + [DisplayName("Количество")] + public int Count { get; set; } + + [DisplayName("Сумма")] + public double Sum { get; set; } + + [DisplayName("Статус")] + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + + [DisplayName("Дата создания")] + public DateTime DateCreate { get; set; } = DateTime.Now; + + [DisplayName("Дата выполнения")] + public DateTime? DateComplete { get; set; } + } +} diff --git a/GarmentFactoryContracts/ViewModels/TextileViewModel.cs b/GarmentFactoryContracts/ViewModels/TextileViewModel.cs new file mode 100644 index 0000000..468b0da --- /dev/null +++ b/GarmentFactoryContracts/ViewModels/TextileViewModel.cs @@ -0,0 +1,20 @@ +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.ViewModels +{ + public class TextileViewModel : ITextileModel + { + public int Id { get; set; } + [DisplayName("Название текстиля")] + public string TextileName { get; set; } = string.Empty; + [DisplayName("Цена")] + public double Price { get; set; } + public Dictionary TextileComponents { get; set; } = new(); + } +} diff --git a/GarmentFactoryDataModels/Enums/OrderStatus.cs b/GarmentFactoryDataModels/Enums/OrderStatus.cs new file mode 100644 index 0000000..c700a33 --- /dev/null +++ b/GarmentFactoryDataModels/Enums/OrderStatus.cs @@ -0,0 +1,11 @@ +namespace GarmentFactoryDataModels.Enums +{ + public enum OrderStatus + { + Неизвестен = -1, + Принят = 0, + Выполняется = 1, + Готов = 2, + Выдан = 3 + } +} \ No newline at end of file diff --git a/GarmentFactoryDataModels/GarmentFactoryDataModels.csproj b/GarmentFactoryDataModels/GarmentFactoryDataModels.csproj new file mode 100644 index 0000000..026e944 --- /dev/null +++ b/GarmentFactoryDataModels/GarmentFactoryDataModels.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/GarmentFactoryDataModels/IId.cs b/GarmentFactoryDataModels/IId.cs new file mode 100644 index 0000000..12143e9 --- /dev/null +++ b/GarmentFactoryDataModels/IId.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryDataModels +{ + public interface IId + { + int Id { get; } + } +} diff --git a/GarmentFactoryDataModels/Models/IComponentModel.cs b/GarmentFactoryDataModels/Models/IComponentModel.cs new file mode 100644 index 0000000..66ca2e5 --- /dev/null +++ b/GarmentFactoryDataModels/Models/IComponentModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryDataModels.Models +{ + public interface IComponentModel : IId + { + string ComponentName { get; } + double Cost { get; } + } +} diff --git a/GarmentFactoryDataModels/Models/IOrderModel.cs b/GarmentFactoryDataModels/Models/IOrderModel.cs new file mode 100644 index 0000000..26c2083 --- /dev/null +++ b/GarmentFactoryDataModels/Models/IOrderModel.cs @@ -0,0 +1,19 @@ +using GarmentFactoryDataModels.Enums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryDataModels.Models +{ + public interface IOrderModel : IId + { + int TextileId { get; } + int Count { get; } + double Sum { get; } + OrderStatus Status { get; } + DateTime DateCreate { get; } + DateTime? DateComplete { get; } + } +} diff --git a/GarmentFactoryDataModels/Models/ITextileModel.cs b/GarmentFactoryDataModels/Models/ITextileModel.cs new file mode 100644 index 0000000..95edba3 --- /dev/null +++ b/GarmentFactoryDataModels/Models/ITextileModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryDataModels.Models +{ + public interface ITextileModel : IId + { + string TextileName { get; } + double Price { get; } + Dictionary TextileComponents { get; } + } +} diff --git a/GarmentFactoryListImplement/DataListSingleton.cs b/GarmentFactoryListImplement/DataListSingleton.cs new file mode 100644 index 0000000..2ae53af --- /dev/null +++ b/GarmentFactoryListImplement/DataListSingleton.cs @@ -0,0 +1,26 @@ +using GarmentFactoryListImplement.Models; + +namespace GarmentFactoryListImplement +{ + public class DataListSingleton + { + private static DataListSingleton? _instance; + public List Components { get; set; } + public List Orders { get; set; } + public List Textiles { get; set; } + private DataListSingleton() + { + Components = new List(); + Orders = new List(); + Textiles = new List(); + } + public static DataListSingleton GetInstance() + { + if (_instance == null) + { + _instance = new DataListSingleton(); + } + return _instance; + } + } +} \ No newline at end of file diff --git a/GarmentFactoryListImplement/GarmentFactoryListImplement.csproj b/GarmentFactoryListImplement/GarmentFactoryListImplement.csproj new file mode 100644 index 0000000..96a2c56 --- /dev/null +++ b/GarmentFactoryListImplement/GarmentFactoryListImplement.csproj @@ -0,0 +1,18 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + diff --git a/GarmentFactoryListImplement/Implements/ComponentStorage.cs b/GarmentFactoryListImplement/Implements/ComponentStorage.cs new file mode 100644 index 0000000..4ea1b58 --- /dev/null +++ b/GarmentFactoryListImplement/Implements/ComponentStorage.cs @@ -0,0 +1,106 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryListImplement.Implements +{ + public class ComponentStorage : IComponentStorage + { + private readonly DataListSingleton _source; + public ComponentStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public List GetFullList() + { + var result = new List(); + foreach (var component in _source.Components) + { + result.Add(component.GetViewModel); + } + return result; + } + public List GetFilteredList(ComponentSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.ComponentName)) + { + return result; + } + foreach (var component in _source.Components) + { + if (component.ComponentName.Contains(model.ComponentName)) + { + result.Add(component.GetViewModel); + } + } + return result; + } + public ComponentViewModel? GetElement(ComponentSearchModel model) + { + if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue) + { + return null; + } + foreach (var component in _source.Components) + { + if ((!string.IsNullOrEmpty(model.ComponentName) && component.ComponentName == model.ComponentName) || (model.Id.HasValue && component.Id == model.Id)) + { + return component.GetViewModel; + } + } + return null; + } + public ComponentViewModel? Insert(ComponentBindingModel model) + { + model.Id = 1; + foreach (var component in _source.Components) + { + if (model.Id <= component.Id) + { + model.Id = component.Id + 1; + } + } + var newComponent = Component.Create(model); + if (newComponent == null) + { + return null; + } + _source.Components.Add(newComponent); + return newComponent.GetViewModel; + } + public ComponentViewModel? Update(ComponentBindingModel model) + { + foreach (var component in _source.Components) + { + if (component.Id == model.Id) + { + component.Update(model); + return component.GetViewModel; + } + } + return null; + } + public ComponentViewModel? Delete(ComponentBindingModel model) + { + for (int i = 0; i < _source.Components.Count; ++i) + { + if (_source.Components[i].Id == model.Id) + { + var element = _source.Components[i]; + _source.Components.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + } +} diff --git a/GarmentFactoryListImplement/Implements/OrderStorage.cs b/GarmentFactoryListImplement/Implements/OrderStorage.cs new file mode 100644 index 0000000..f9b0774 --- /dev/null +++ b/GarmentFactoryListImplement/Implements/OrderStorage.cs @@ -0,0 +1,137 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryListImplement.Implements +{ + public class OrderStorage : IOrderStorage + { + private readonly DataListSingleton _source; + public OrderStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public List GetFullList() + { + var result = new List(); + + foreach (var order in _source.Orders) + { + result.Add(AddTextileName(order.GetViewModel)); + } + + return result; + } + + public List GetFilteredList(OrderSearchModel model) + { + var result = new List(); + + if (model == null || !model.Id.HasValue) + { + return result; + } + + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + result.Add(AddTextileName(order.GetViewModel)); + } + } + + return result; + } + + public OrderViewModel? GetElement(OrderSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } + + foreach (var order in _source.Orders) + { + if (model.Id.HasValue && order.Id == model.Id) + { + return AddTextileName(order.GetViewModel); + } + } + + return null; + } + + public OrderViewModel? Insert(OrderBindingModel model) + { + model.Id = 1; + + foreach (var order in _source.Orders) + { + if (model.Id <= order.Id) + { + model.Id = order.Id + 1; + } + } + + var newOrder = Order.Create(model); + + if (newOrder == null) + { + return null; + } + + _source.Orders.Add(newOrder); + + return AddTextileName(newOrder.GetViewModel); + } + + public OrderViewModel? Update(OrderBindingModel model) + { + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + order.Update(model); + return AddTextileName(order.GetViewModel); + } + } + + return null; + } + + public OrderViewModel? Delete(OrderBindingModel model) + { + for (int i = 0; i < _source.Orders.Count; ++i) + { + if (_source.Orders[i].Id == model.Id) + { + var element = _source.Orders[i]; + _source.Orders.RemoveAt(i); + return AddTextileName(element.GetViewModel); + } + } + return null; + } + + private OrderViewModel AddTextileName(OrderViewModel model) + { + foreach (var textile in _source.Textiles) + { + if (textile.Id == model.TextileId) + { + model.TextileName = textile.TextileName; + return model; + } + } + return model; + } + } +} diff --git a/GarmentFactoryListImplement/Implements/TextileStorage.cs b/GarmentFactoryListImplement/Implements/TextileStorage.cs new file mode 100644 index 0000000..e6ddd27 --- /dev/null +++ b/GarmentFactoryListImplement/Implements/TextileStorage.cs @@ -0,0 +1,121 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryListImplement.Implements +{ + public class TextileStorage : ITextileStorage + { + private readonly DataListSingleton _source; + + public TextileStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public List GetFullList() + { + var result = new List(); + + foreach (var textile in _source.Textiles) + { + result.Add(textile.GetViewModel); + } + + return result; + } + + public List GetFilteredList(TextileSearchModel model) + { + var result = new List(); + + if (string.IsNullOrEmpty(model.TextileName)) + { + return result; + } + + foreach (var textile in _source.Textiles) + { + if (textile.TextileName.Contains(model.TextileName)) + { + result.Add(textile.GetViewModel); + } + } + return result; + } + + public TextileViewModel? GetElement(TextileSearchModel model) + { + if (string.IsNullOrEmpty(model.TextileName) && !model.Id.HasValue) + { + return null; + } + + foreach (var textile in _source.Textiles) + { + if ((!string.IsNullOrEmpty(model.TextileName) && textile.TextileName == model.TextileName) || (model.Id.HasValue && textile.Id == model.Id)) + { + return textile.GetViewModel; + } + } + return null; + } + + public TextileViewModel? Insert(TextileBindingModel model) + { + model.Id = 1; + + foreach (var textile in _source.Textiles) + { + if (model.Id <= textile.Id) + { + model.Id = textile.Id + 1; + } + } + + var newTextile = Textile.Create(model); + + if (newTextile == null) + { + return null; + } + + _source.Textiles.Add(newTextile); + return newTextile.GetViewModel; + } + + public TextileViewModel? Update(TextileBindingModel model) + { + foreach (var textile in _source.Textiles) + { + if (textile.Id == model.Id) + { + textile.Update(model); + return textile.GetViewModel; + } + } + return null; + } + + public TextileViewModel? Delete(TextileBindingModel model) + { + for (int i = 0; i < _source.Textiles.Count; ++i) + { + if (_source.Textiles[i].Id == model.Id) + { + var element = _source.Textiles[i]; + _source.Textiles.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + } +} diff --git a/GarmentFactoryListImplement/Models/Component.cs b/GarmentFactoryListImplement/Models/Component.cs new file mode 100644 index 0000000..e9d1672 --- /dev/null +++ b/GarmentFactoryListImplement/Models/Component.cs @@ -0,0 +1,46 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryListImplement.Models +{ + public class Component : IComponentModel + { + public int Id { get; private set; } + public string ComponentName { get; private set; } = string.Empty; + public double Cost { get; set; } + public static Component? Create(ComponentBindingModel? model) + { + if (model == null) + { + return null; + } + return new Component() + { + Id = model.Id, + ComponentName = model.ComponentName, + Cost = model.Cost + }; + } + public void Update(ComponentBindingModel? model) + { + if (model == null) + { + return; + } + ComponentName = model.ComponentName; + Cost = model.Cost; + } + public ComponentViewModel GetViewModel => new() + { + Id = Id, + ComponentName = ComponentName, + Cost = Cost + }; + } +} diff --git a/GarmentFactoryListImplement/Models/Order.cs b/GarmentFactoryListImplement/Models/Order.cs new file mode 100644 index 0000000..f3303c2 --- /dev/null +++ b/GarmentFactoryListImplement/Models/Order.cs @@ -0,0 +1,65 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDataModels.Enums; +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryListImplement.Models +{ + public class Order : IOrderModel + { + public int Id { get; private set; } + public int TextileId { get; private set; } + public int Count { get; set; } + public double Sum { get; set; } + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + public DateTime DateCreate { get; set; } = DateTime.Now; + public DateTime? DateComplete { get; set; } + + public static Order? Create(OrderBindingModel? model) + { + if (model == null) + { + return null; + } + return new Order() + { + Id = model.Id, + TextileId = model.TextileId, + Count = model.Count, + Sum = model.Sum, + Status = model.Status, + DateCreate = model.DateCreate, + DateComplete = model.DateComplete + }; + } + + public void Update(OrderBindingModel? model) + { + if (model == null) + { + return; + } + Status = model.Status; + if (model.Status == OrderStatus.Выдан) + { + DateComplete = model.DateComplete; + } + } + + public OrderViewModel GetViewModel => new() + { + Id = Id, + TextileId = TextileId, + Count = Count, + Sum = Sum, + Status = Status, + DateCreate = DateCreate, + DateComplete = DateComplete + }; + } +} diff --git a/GarmentFactoryListImplement/Models/Textile.cs b/GarmentFactoryListImplement/Models/Textile.cs new file mode 100644 index 0000000..0243cf5 --- /dev/null +++ b/GarmentFactoryListImplement/Models/Textile.cs @@ -0,0 +1,50 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryListImplement.Models +{ + public class Textile : ITextileModel + { + public int Id { get; private set; } + public string TextileName { get; private set; } = string.Empty; + public double Price { get; private set; } + public Dictionary TextileComponents { get; private set; } = new Dictionary(); + public static Textile? Create(TextileBindingModel? model) + { + if (model == null) + { + return null; + } + return new Textile() + { + Id = model.Id, + TextileName = model.TextileName, + Price = model.Price, + TextileComponents = model.TextileComponents + }; + } + public void Update(TextileBindingModel? model) + { + if (model == null) + { + return; + } + TextileName = model.TextileName; + Price = model.Price; + TextileComponents = model.TextileComponents; + } + public TextileViewModel GetViewModel => new() + { + Id = Id, + TextileName = TextileName, + Price = Price, + TextileComponents = TextileComponents + }; + } +} -- 2.25.1