From be0302ba630d8ea2b8bf48d3b068d34c34ff869f Mon Sep 17 00:00:00 2001 From: "ityurner02@mail.ru" Date: Tue, 28 Mar 2023 22:01:07 +0400 Subject: [PATCH] =?UTF-8?q?=D0=A3=D1=81=D0=BB=D0=BE=D0=B6=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0?= =?UTF-8?q?=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../PlumbingRepair/FormComponents.cs | 1 + .../PlumbingRepair/FormMain.Designer.cs | 13 ++ PlumbingRepair/PlumbingRepair/FormMain.cs | 11 ++ .../PlumbingRepair/FormSellWork.Designer.cs | 124 ++++++++++++++++++ PlumbingRepair/PlumbingRepair/FormSellWork.cs | 94 +++++++++++++ .../PlumbingRepair/FormSellWork.resx | 60 +++++++++ .../PlumbingRepair/FormStore.Designer.cs | 40 ++++-- PlumbingRepair/PlumbingRepair/FormStore.cs | 104 +++++++-------- PlumbingRepair/PlumbingRepair/FormStores.cs | 2 +- PlumbingRepair/PlumbingRepair/FormWorks.cs | 1 + PlumbingRepair/PlumbingRepair/Program.cs | 1 + .../BusinessLogic/OrderLogic.cs | 37 +++++- .../BusinessLogic/StoreLogic.cs | 88 +++++++++++-- .../BindingModels/StoreBindingModel.cs | 4 +- .../BusinessLogicsContracts/IStoreLogic.cs | 2 + .../StoragesContracts/IStoreStorage.cs | 2 + .../ViewModels/StoreViewModel.cs | 4 +- .../Models/IStoreModel.cs | 3 +- .../Implements/StoreStorage.cs | 6 + .../Models/Store.cs | 10 +- .../DataFileSingleton.cs | 5 + .../Implements/StoreStorage.cs | 109 +++++++++++++++ .../Models/Store.cs | 103 +++++++++++++++ 23 files changed, 734 insertions(+), 90 deletions(-) create mode 100644 PlumbingRepair/PlumbingRepair/FormSellWork.Designer.cs create mode 100644 PlumbingRepair/PlumbingRepair/FormSellWork.cs create mode 100644 PlumbingRepair/PlumbingRepair/FormSellWork.resx create mode 100644 PlumbingRepair/PlumpingRepairFileImplement/Implements/StoreStorage.cs create mode 100644 PlumbingRepair/PlumpingRepairFileImplement/Models/Store.cs diff --git a/PlumbingRepair/PlumbingRepair/FormComponents.cs b/PlumbingRepair/PlumbingRepair/FormComponents.cs index 685ca8d..f87922b 100644 --- a/PlumbingRepair/PlumbingRepair/FormComponents.cs +++ b/PlumbingRepair/PlumbingRepair/FormComponents.cs @@ -14,6 +14,7 @@ namespace PlumbingRepair InitializeComponent(); _logger = logger; _logic = logic; + LoadData(); } private void FormComponents_Load(object sender, EventArgs e) diff --git a/PlumbingRepair/PlumbingRepair/FormMain.Designer.cs b/PlumbingRepair/PlumbingRepair/FormMain.Designer.cs index 003036e..8566862 100644 --- a/PlumbingRepair/PlumbingRepair/FormMain.Designer.cs +++ b/PlumbingRepair/PlumbingRepair/FormMain.Designer.cs @@ -40,6 +40,7 @@ this.IssuedOrderButton = new System.Windows.Forms.Button(); this.UpdateListButton = new System.Windows.Forms.Button(); this.StoreReplenishment = new System.Windows.Forms.Button(); + this.SellWorkButton = new System.Windows.Forms.Button(); this.MenuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit(); this.SuspendLayout(); @@ -153,12 +154,23 @@ this.StoreReplenishment.Text = "Пополнение магазина"; this.StoreReplenishment.UseVisualStyleBackColor = true; this.StoreReplenishment.Click += new System.EventHandler(this.StoreReplenishment_Click); + // + // SellPackageButton // + this.SellWorkButton.Location = new System.Drawing.Point(728, 385); + this.SellWorkButton.Name = "SellWorkButton"; + this.SellWorkButton.Size = new System.Drawing.Size(125, 31); + this.SellWorkButton.TabIndex = 8; + this.SellWorkButton.Text = "Продать изделие"; + this.SellWorkButton.UseVisualStyleBackColor = true; + this.SellWorkButton.Click += new System.EventHandler(this.SellWorkButton_Click); + // // FormMain // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(865, 450); + this.Controls.Add(this.SellWorkButton); this.Controls.Add(this.StoreReplenishment); this.Controls.Add(this.UpdateListButton); this.Controls.Add(this.IssuedOrderButton); @@ -193,5 +205,6 @@ private Button UpdateListButton; private ToolStripMenuItem StoreToolStripMenuItem; private Button StoreReplenishment; + private Button SellWorkButton; } } \ No newline at end of file diff --git a/PlumbingRepair/PlumbingRepair/FormMain.cs b/PlumbingRepair/PlumbingRepair/FormMain.cs index 04de025..c4df2a0 100644 --- a/PlumbingRepair/PlumbingRepair/FormMain.cs +++ b/PlumbingRepair/PlumbingRepair/FormMain.cs @@ -15,6 +15,7 @@ namespace PlumbingRepair InitializeComponent(); _logger = logger; _orderLogic = orderLogic; + LoadData(); } private void FormMain_Load(object sender, EventArgs e) @@ -206,5 +207,15 @@ namespace PlumbingRepair form.ShowDialog(); } } + + private void SellWorkButton_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSellWork)); + + if (service is FormSellWork form) + { + form.ShowDialog(); + } + } } } diff --git a/PlumbingRepair/PlumbingRepair/FormSellWork.Designer.cs b/PlumbingRepair/PlumbingRepair/FormSellWork.Designer.cs new file mode 100644 index 0000000..bea8c38 --- /dev/null +++ b/PlumbingRepair/PlumbingRepair/FormSellWork.Designer.cs @@ -0,0 +1,124 @@ +namespace PlumbingRepair +{ + partial class FormSellWork + { + /// + /// 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() + { + WorkLabel = new Label(); + QuantityLabel = new Label(); + WorkСomboBox = new ComboBox(); + QuantityTextBox = new TextBox(); + SaveButton = new Button(); + ButtonCancel = new Button(); + SuspendLayout(); + // + // WorkLabel + // + WorkLabel.AutoSize = true; + WorkLabel.Location = new Point(14, 24); + WorkLabel.Name = "WorkLabel"; + WorkLabel.Size = new Size(71, 20); + WorkLabel.TabIndex = 0; + WorkLabel.Text = "Изделие:"; + // + // QuantityLabel + // + QuantityLabel.AutoSize = true; + QuantityLabel.Location = new Point(14, 68); + QuantityLabel.Name = "QuantityLabel"; + QuantityLabel.Size = new Size(93, 20); + QuantityLabel.TabIndex = 1; + QuantityLabel.Text = "Количество:"; + // + // WorkСomboBox + // + WorkСomboBox.FormattingEnabled = true; + WorkСomboBox.Location = new Point(101, 20); + WorkСomboBox.Margin = new Padding(3, 4, 3, 4); + WorkСomboBox.Name = "WorkСomboBox"; + WorkСomboBox.Size = new Size(210, 28); + WorkСomboBox.TabIndex = 2; + // + // QuantityTextBox + // + QuantityTextBox.Location = new Point(101, 64); + QuantityTextBox.Margin = new Padding(3, 4, 3, 4); + QuantityTextBox.Name = "QuantityTextBox"; + QuantityTextBox.Size = new Size(210, 27); + QuantityTextBox.TabIndex = 3; + // + // SaveButton + // + SaveButton.Location = new Point(82, 133); + SaveButton.Margin = new Padding(3, 4, 3, 4); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(111, 39); + SaveButton.TabIndex = 4; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // ButtonCancel + // + ButtonCancel.Location = new Point(200, 133); + ButtonCancel.Margin = new Padding(3, 4, 3, 4); + ButtonCancel.Name = "ButtonCancel"; + ButtonCancel.Size = new Size(111, 39); + ButtonCancel.TabIndex = 5; + ButtonCancel.Text = "Отмена"; + ButtonCancel.UseVisualStyleBackColor = true; + ButtonCancel.Click += ButtonCancel_Click; + // + // FormSellWork + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(325, 188); + Controls.Add(ButtonCancel); + Controls.Add(SaveButton); + Controls.Add(QuantityTextBox); + Controls.Add(WorkСomboBox); + Controls.Add(QuantityLabel); + Controls.Add(WorkLabel); + Margin = new Padding(3, 4, 3, 4); + Name = "FormSellWork"; + Text = "Продать Изделие"; + Load += FormSellWork_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label WorkLabel; + private Label QuantityLabel; + private ComboBox WorkСomboBox; + private TextBox QuantityTextBox; + private Button SaveButton; + private Button ButtonCancel; + } +} \ No newline at end of file diff --git a/PlumbingRepair/PlumbingRepair/FormSellWork.cs b/PlumbingRepair/PlumbingRepair/FormSellWork.cs new file mode 100644 index 0000000..a1bcfff --- /dev/null +++ b/PlumbingRepair/PlumbingRepair/FormSellWork.cs @@ -0,0 +1,94 @@ +using Microsoft.Extensions.Logging; +using PlumbingRepairContracts.BusinessLogicsContracts; +using PlumbingRepairContracts.SearchModels; + +namespace PlumbingRepair +{ + public partial class FormSellWork : Form + { + private readonly ILogger _logger; + private readonly IWorkLogic _logicWork; + private readonly IStoreLogic _logicStore; + public FormSellWork(ILogger logger, IWorkLogic logicPackage, IStoreLogic logicStore) + { + InitializeComponent(); + _logger = logger; + _logicWork = logicPackage; + _logicStore = logicStore; + LoadData(); + } + + private void FormSellWork_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + _logger.LogInformation("Loading works for sale."); + + try + { + var list = _logicWork.ReadList(null); + if (list != null) + { + WorkСomboBox.DisplayMember = "WorkName"; + WorkСomboBox.ValueMember = "Id"; + WorkСomboBox.DataSource = list; + WorkСomboBox.SelectedItem = null; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "List loading error."); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(QuantityTextBox.Text)) + { + MessageBox.Show("Укажите количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + if (WorkСomboBox.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + _logger.LogInformation("Work sale."); + + try + { + var operationResult = _logicStore.SellWork(_logicWork.ReadElement(new WorkSearchModel() + { + Id = Convert.ToInt32(WorkСomboBox.SelectedValue) + })!, Convert.ToInt32(QuantityTextBox.Text)); + + if (!operationResult) + { + throw new Exception("Ошибка при продаже изделия. Дополнительная информация в логах."); + } + + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Work sale error."); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/PlumbingRepair/PlumbingRepair/FormSellWork.resx b/PlumbingRepair/PlumbingRepair/FormSellWork.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/PlumbingRepair/PlumbingRepair/FormSellWork.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/PlumbingRepair/PlumbingRepair/FormStore.Designer.cs b/PlumbingRepair/PlumbingRepair/FormStore.Designer.cs index d8fcdfb..9f55ef9 100644 --- a/PlumbingRepair/PlumbingRepair/FormStore.Designer.cs +++ b/PlumbingRepair/PlumbingRepair/FormStore.Designer.cs @@ -40,7 +40,10 @@ this.SaveButton = new System.Windows.Forms.Button(); this.ButtonCancel = new System.Windows.Forms.Button(); this.OpeningDatePicker = new System.Windows.Forms.DateTimePicker(); + this.VolumeNumericUpDown = new System.Windows.Forms.NumericUpDown(); + this.WorkMaxCountLable = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.VolumeNumericUpDown)).BeginInit(); this.SuspendLayout(); // // StoreNameLabel @@ -70,10 +73,10 @@ this.OpeningDateLabel.TabIndex = 2; this.OpeningDateLabel.Text = "Дата открытия: "; // - // NameComboBox + // NameTextBox // this.NameTextBox.Location = new System.Drawing.Point(137, 6); - this.NameTextBox.Name = "NameComboBox"; + this.NameTextBox.Name = "NameTextBox"; this.NameTextBox.Size = new System.Drawing.Size(174, 23); this.NameTextBox.TabIndex = 3; // @@ -97,21 +100,21 @@ this.DataGridView.Size = new System.Drawing.Size(776, 288); this.DataGridView.TabIndex = 6; // - // PackageName + // WorkName // this.WorkName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.WorkName.HeaderText = "Название изделия"; - this.WorkName.Name = "PackageName"; + this.WorkName.Name = "WorkName"; // - // PackagePrice + // WorkPrice // this.WorkPrice.HeaderText = "Цена"; - this.WorkPrice.Name = "PackagePrice"; + this.WorkPrice.Name = "WorkPrice"; // - // PackageCount + // WorkCount // this.WorkCount.HeaderText = "Количество"; - this.WorkCount.Name = "PackageCount"; + this.WorkCount.Name = "WorkCount"; // // SaveButton // @@ -139,12 +142,30 @@ this.OpeningDatePicker.Name = "OpeningDatePicker"; this.OpeningDatePicker.Size = new System.Drawing.Size(174, 23); this.OpeningDatePicker.TabIndex = 9; + // + // VolumeNumericUpDown + // + this.VolumeNumericUpDown.Location = new System.Drawing.Point(486, 7); + this.VolumeNumericUpDown.Name = "VolumeNumericUpDown"; + this.VolumeNumericUpDown.Size = new System.Drawing.Size(168, 23); + this.VolumeNumericUpDown.TabIndex = 10; + // + // WorkMaxCountLable + // + this.WorkMaxCountLable.AutoSize = true; + this.WorkMaxCountLable.Location = new System.Drawing.Point(340, 9); + this.WorkMaxCountLable.Name = "WorkMaxCountLable"; + this.WorkMaxCountLable.Size = new System.Drawing.Size(140, 15); + this.WorkMaxCountLable.TabIndex = 11; + this.WorkMaxCountLable.Text = "Вместимость магазина: "; // // FormStore // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.WorkMaxCountLable); + this.Controls.Add(this.VolumeNumericUpDown); this.Controls.Add(this.OpeningDatePicker); this.Controls.Add(this.ButtonCancel); this.Controls.Add(this.SaveButton); @@ -158,6 +179,7 @@ this.Text = "Изделия магазина"; this.Load += new System.EventHandler(this.FormStore_Load); ((System.ComponentModel.ISupportInitialize)(this.DataGridView)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.VolumeNumericUpDown)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); @@ -177,5 +199,7 @@ private DataGridViewTextBoxColumn WorkPrice; private DataGridViewTextBoxColumn WorkCount; private DateTimePicker OpeningDatePicker; + private NumericUpDown VolumeNumericUpDown; + private Label WorkMaxCountLable; } } \ No newline at end of file diff --git a/PlumbingRepair/PlumbingRepair/FormStore.cs b/PlumbingRepair/PlumbingRepair/FormStore.cs index ad36d7c..a530165 100644 --- a/PlumbingRepair/PlumbingRepair/FormStore.cs +++ b/PlumbingRepair/PlumbingRepair/FormStore.cs @@ -1,42 +1,30 @@ using Microsoft.Extensions.Logging; using PlumbingRepairContracts.BindingModels; using PlumbingRepairContracts.BusinessLogicsContracts; +using PlumbingRepairContracts.SearchModels; using PlumbingRepairContracts.ViewModels; using PlumbingRepairDataModels.Models; +using System.Reflection; +using System.Windows.Forms; namespace PlumbingRepair { public partial class FormStore : Form { - private readonly List? _listStores; private readonly IStoreLogic _logic; private readonly ILogger _logger; - public int Id { get; set; } + private int? _id; + private Dictionary _listStores; + public int Id { set { _id = value; } } public FormStore(ILogger logger, IStoreLogic logic) { InitializeComponent(); _logger = logger; - _listStores = logic.ReadList(null); + _listStores = new(); _logic = logic; } - private IStoreModel? GetStore(int id) - { - if (_listStores == null) - { - return null; - } - foreach (var elem in _listStores) - { - if (elem.Id == id) - { - return elem; - } - } - return null; - } - private void SaveButton_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(NameTextBox.Text)) @@ -44,49 +32,34 @@ namespace PlumbingRepair MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - if (string.IsNullOrEmpty(AdressTextBox.Text)) { MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - - _logger.LogInformation("Сохранение изделия"); - + _logger.LogInformation("Сохранение магазина"); try { - DateTime.TryParse(OpeningDatePicker.Text, out var dateTime); - StoreBindingModel model = new() + var model = new StoreBindingModel { + Id = _id ?? 0, StoreName = NameTextBox.Text, StoreAdress = AdressTextBox.Text, - OpeningDate = dateTime + OpeningDate = OpeningDatePicker.Value.Date, + WorkMaxCount = (int)VolumeNumericUpDown.Value }; - var vmodel = GetStore(Id); - bool operationResult = false; - - if (vmodel != null) - { - model.Id = vmodel.Id; - operationResult = _logic.Update(model); - } - else - { - operationResult = _logic.Create(model); - } - + 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, "Ошибка сохранения изделия"); + _logger.LogError(ex, "Ошибка сохранения магазина"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -99,37 +72,52 @@ namespace PlumbingRepair private void FormStore_Load(object sender, EventArgs e) { - LoadData(); + if (_id.HasValue) + { + _logger.LogInformation("Загрузка магазина"); + try + { + var view = _logic.ReadElement(new StoreSearchModel + { + Id = _id.Value + }); + if (view != null) + { + NameTextBox.Text = view.StoreName; + AdressTextBox.Text = view.StoreAdress; + OpeningDatePicker.Text = view.OpeningDate.ToString(); + VolumeNumericUpDown.Value = view.WorkMaxCount; + _listStores = view.StoreWorks ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } } private void LoadData(bool extendDate = true) { + _logger.LogInformation("Загрузка изделий магазина"); try { - var model = GetStore(extendDate ? Id : Convert.ToInt32(NameTextBox.Text)); - if (model != null) + if (_listStores != null) { - NameTextBox.Text = model.StoreName; - AdressTextBox.Text = model.StoreAdress; - OpeningDatePicker.Text = Convert.ToString(model.OpeningDate); DataGridView.Rows.Clear(); - foreach (var el in model.Works.Values) + foreach (var elem in _listStores) { - DataGridView.Rows.Add(new object[] { el.Item1.WorkName, el.Item1.Price, el.Item2 }); + DataGridView.Rows.Add(new object[] { elem.Key, elem.Value.Item1.WorkName, elem.Value.Item2 }); } } - _logger.LogInformation("Загрузка магазинов"); } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки магазинов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка загрузки изделий магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - - private void NameComboBox_SelectedIndexChanged(object sender, EventArgs e) - { - LoadData(false); - } } } diff --git a/PlumbingRepair/PlumbingRepair/FormStores.cs b/PlumbingRepair/PlumbingRepair/FormStores.cs index 0036410..9995eef 100644 --- a/PlumbingRepair/PlumbingRepair/FormStores.cs +++ b/PlumbingRepair/PlumbingRepair/FormStores.cs @@ -31,7 +31,7 @@ namespace PlumbingRepair DataGridView.DataSource = list; DataGridView.Columns["Id"].Visible = false; DataGridView.Columns["StoreName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - DataGridView.Columns["Works"].Visible = false; + DataGridView.Columns["StoreWorks"].Visible = false; } _logger.LogInformation("Загрузка магазинов"); diff --git a/PlumbingRepair/PlumbingRepair/FormWorks.cs b/PlumbingRepair/PlumbingRepair/FormWorks.cs index 5cbebac..cc5face 100644 --- a/PlumbingRepair/PlumbingRepair/FormWorks.cs +++ b/PlumbingRepair/PlumbingRepair/FormWorks.cs @@ -14,6 +14,7 @@ namespace PlumbingRepair InitializeComponent(); _logger = logger; _logic = logic; + LoadData(); } private void FormComponents_Load(object sender, EventArgs e) diff --git a/PlumbingRepair/PlumbingRepair/Program.cs b/PlumbingRepair/PlumbingRepair/Program.cs index 7b7746c..1a04a42 100644 --- a/PlumbingRepair/PlumbingRepair/Program.cs +++ b/PlumbingRepair/PlumbingRepair/Program.cs @@ -52,6 +52,7 @@ namespace PlumbingRepair services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/PlumbingRepair/PlumbingRepairBusinessLogic/BusinessLogic/OrderLogic.cs b/PlumbingRepair/PlumbingRepairBusinessLogic/BusinessLogic/OrderLogic.cs index dbb06f3..33226c1 100644 --- a/PlumbingRepair/PlumbingRepairBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/PlumbingRepair/PlumbingRepairBusinessLogic/BusinessLogic/OrderLogic.cs @@ -12,11 +12,15 @@ namespace PlumbingRepairBusinessLogic.BusinessLogic { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly IStoreLogic _storeLogic; + private readonly IWorkStorage _workStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IWorkStorage workStorage, IStoreLogic storeLogic) { _logger = logger; _orderStorage = orderStorage; + _storeLogic = storeLogic; + _workStorage = workStorage; } public bool CreateOrder(OrderBindingModel model) @@ -43,9 +47,14 @@ namespace PlumbingRepairBusinessLogic.BusinessLogic public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) { - CheckModel(model); + var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); - if (model.Status + 1 != newStatus) + if (viewModel == null) + { + throw new ArgumentNullException(nameof(model)); + } + + if (viewModel.Status + 1 != newStatus) { _logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Order status incorrect."); return false; @@ -53,9 +62,29 @@ namespace PlumbingRepairBusinessLogic.BusinessLogic model.Status = newStatus; - if (model.Status == OrderStatus.Выдан) + if (model.Status == OrderStatus.Готов) + { model.DateImplement = DateTime.Now; + var work = _workStorage.GetElement(new() { Id = viewModel.WorkId }); + + if (work == null) + { + throw new ArgumentNullException(nameof(work)); + } + + if (!_storeLogic.AddWork(work, viewModel.Count)) + { + throw new Exception($"AddWork operation failed. Store is full."); + } + } + else + { + model.DateImplement = viewModel.DateImplement; + } + + CheckModel(model, false); + if (_orderStorage.Update(model) == null) { model.Status--; diff --git a/PlumbingRepair/PlumbingRepairBusinessLogic/BusinessLogic/StoreLogic.cs b/PlumbingRepair/PlumbingRepairBusinessLogic/BusinessLogic/StoreLogic.cs index 713d275..04d312b 100644 --- a/PlumbingRepair/PlumbingRepairBusinessLogic/BusinessLogic/StoreLogic.cs +++ b/PlumbingRepair/PlumbingRepairBusinessLogic/BusinessLogic/StoreLogic.cs @@ -26,29 +26,34 @@ namespace PlumbingRepairBusinessLogic.BusinessLogic if (quantity <= 0) { - throw new ArgumentException("Количество добавляемого изделия должно быть больше 0", nameof(quantity)); + throw new ArgumentException("Количество изделий должно быть больше 0", nameof(quantity)); } - _logger.LogInformation("AddWorkInStore. StoreName:{StoreName}.Id:{ Id}", model.StoreName, model.Id); + _logger.LogInformation("AddWork. StoreName:{StoreName}.Id:{ Id}", model.StoreName, model.Id); var element = _storeStorage.GetElement(model); if (element == null) { - _logger.LogWarning("AddWorkInStore element not found"); + _logger.LogWarning("AddWork element not found"); return false; } - _logger.LogInformation("AddWorkInStore find. Id:{Id}", element.Id); - - if (element.Works.TryGetValue(work.Id, out var pair)) + if (element.WorkMaxCount - element.StoreWorks.Select(x => x.Value.Item2).Sum() < quantity) { - element.Works[work.Id] = (work, quantity + pair.Item2); - _logger.LogInformation("AddWorkInStore. Has been added {quantity} {work} in {StoreName}", quantity, work.WorkName, element.StoreName); + throw new ArgumentNullException("Магазин переполнен", nameof(quantity)); + } + + _logger.LogInformation("AddWork find. Id:{Id}", element.Id); + + if (element.StoreWorks.TryGetValue(work.Id, out var pair)) + { + element.StoreWorks[work.Id] = (work, quantity + pair.Item2); + _logger.LogInformation("AddWork. Added {quantity} {work} to '{StoreName}' store", quantity, work.WorkName, element.StoreName); } else { - element.Works[work.Id] = (work, quantity); - _logger.LogInformation("AddWorkInShop. Has been added {quantity} new Work {work} in {StoreName}", quantity, work.WorkName, element.StoreName); + element.StoreWorks[work.Id] = (work, quantity); + _logger.LogInformation("AddWork. Added {quantity} new package {package} to '{StoreName}' store", quantity, work.WorkName, element.StoreName); } _storeStorage.Update(new() @@ -57,15 +62,63 @@ namespace PlumbingRepairBusinessLogic.BusinessLogic StoreAdress = element.StoreAdress, StoreName = element.StoreName, OpeningDate = element.OpeningDate, - Works = element.Works + WorkMaxCount = element.WorkMaxCount, + StoreWorks = element.StoreWorks }); return true; } + public bool AddWork(IWorkModel work, int quantity) + { + if (work == null) + { + throw new ArgumentNullException(nameof(work)); + } + + if (quantity <= 0) + { + throw new ArgumentException("Количество добавляемого изделия должно быть больше 0", nameof(quantity)); + } + + var freePlaces = _storeStorage.GetFullList() + .Select(x => x.WorkMaxCount - x.StoreWorks + .Select(p => p.Value.Item2).Sum()).Sum() - quantity; + + if (freePlaces < 0) + { + _logger.LogInformation("AddWork. Failed to add work to store. It's full."); + return false; + } + + foreach (var store in _storeStorage.GetFullList()) + { + var temp = Math.Min(quantity, store.WorkMaxCount - store.StoreWorks.Select(x => x.Value.Item2).Sum()); + + if (temp <= 0) + { + continue; + } + + if (!AddWork(new() { Id = store.Id }, work, temp)) + { + _logger.LogWarning("An error occurred while adding work to stores"); + return false; + } + + quantity -= temp; + + if (quantity == 0) + { + return true; + } + } + return true; + } + public bool Create(StoreBindingModel model) { CheckModel(model); - model.Works = new(); + model.StoreWorks = new(); if (_storeStorage.Insert(model) == null) { @@ -126,6 +179,11 @@ namespace PlumbingRepairBusinessLogic.BusinessLogic return list; } + public bool SellWork(IWorkModel work, int quantity) + { + return _storeStorage.SellWork(work, quantity); + } + public bool Update(StoreBindingModel model) { CheckModel(model, false); @@ -160,7 +218,13 @@ namespace PlumbingRepairBusinessLogic.BusinessLogic throw new ArgumentNullException("Нет названия магазина", nameof(model.StoreName)); } + if (model.WorkMaxCount < 0) + { + throw new ArgumentException("Максимальное количество изделий в магазине не может быть меньше нуля", nameof(model.WorkMaxCount)); + } + _logger.LogInformation("Store. StoreName:{0}.StoreAdress:{1}. Id: {2}", model.StoreName, model.StoreAdress, model.Id); + var element = _storeStorage.GetElement(new StoreSearchModel { StoreName = model.StoreName diff --git a/PlumbingRepair/PlumbingRepairContracts/BindingModels/StoreBindingModel.cs b/PlumbingRepair/PlumbingRepairContracts/BindingModels/StoreBindingModel.cs index 8aadd3a..62d35e5 100644 --- a/PlumbingRepair/PlumbingRepairContracts/BindingModels/StoreBindingModel.cs +++ b/PlumbingRepair/PlumbingRepairContracts/BindingModels/StoreBindingModel.cs @@ -9,8 +9,10 @@ namespace PlumbingRepairContracts.BindingModels public DateTime OpeningDate { get; set; } = DateTime.Now; - public Dictionary Works { get; set; } = new(); + public Dictionary StoreWorks { get; set; } = new(); public int Id { get; set; } + + public int WorkMaxCount { get; set; } } } diff --git a/PlumbingRepair/PlumbingRepairContracts/BusinessLogicsContracts/IStoreLogic.cs b/PlumbingRepair/PlumbingRepairContracts/BusinessLogicsContracts/IStoreLogic.cs index eb93eec..c5de7d8 100644 --- a/PlumbingRepair/PlumbingRepairContracts/BusinessLogicsContracts/IStoreLogic.cs +++ b/PlumbingRepair/PlumbingRepairContracts/BusinessLogicsContracts/IStoreLogic.cs @@ -13,5 +13,7 @@ namespace PlumbingRepairContracts.BusinessLogicsContracts bool Update(StoreBindingModel model); bool Delete(StoreBindingModel model); bool AddWork(StoreSearchModel model, IWorkModel work, int quantity); + bool AddWork(IWorkModel package, int quantity); + bool SellWork(IWorkModel package, int quantity); } } diff --git a/PlumbingRepair/PlumbingRepairContracts/StoragesContracts/IStoreStorage.cs b/PlumbingRepair/PlumbingRepairContracts/StoragesContracts/IStoreStorage.cs index 34b9c18..7cc5e22 100644 --- a/PlumbingRepair/PlumbingRepairContracts/StoragesContracts/IStoreStorage.cs +++ b/PlumbingRepair/PlumbingRepairContracts/StoragesContracts/IStoreStorage.cs @@ -1,6 +1,7 @@ using PlumbingRepairContracts.BindingModels; using PlumbingRepairContracts.SearchModels; using PlumbingRepairContracts.ViewModels; +using PlumbingRepairDataModels.Models; namespace PlumbingRepairContracts.StoragesContracts { @@ -12,5 +13,6 @@ namespace PlumbingRepairContracts.StoragesContracts StoreViewModel? Insert(StoreBindingModel model); StoreViewModel? Update(StoreBindingModel model); StoreViewModel? Delete(StoreBindingModel model); + bool SellWork(IWorkModel model, int quantity); } } diff --git a/PlumbingRepair/PlumbingRepairContracts/ViewModels/StoreViewModel.cs b/PlumbingRepair/PlumbingRepairContracts/ViewModels/StoreViewModel.cs index 9642281..cccca84 100644 --- a/PlumbingRepair/PlumbingRepairContracts/ViewModels/StoreViewModel.cs +++ b/PlumbingRepair/PlumbingRepairContracts/ViewModels/StoreViewModel.cs @@ -5,7 +5,7 @@ namespace PlumbingRepairContracts.ViewModels { public class StoreViewModel : IStoreModel { - public Dictionary Works { get; set; } = new(); + public Dictionary StoreWorks { get; set; } = new(); public int Id { get; set; } [DisplayName("Название магазина")] @@ -14,5 +14,7 @@ namespace PlumbingRepairContracts.ViewModels public string StoreAdress { get; set; } = string.Empty; [DisplayName("Дата открытия")] public DateTime OpeningDate { get; set; } = DateTime.Now; + [DisplayName("Вместимость магазина")] + public int WorkMaxCount { get; set; } } } diff --git a/PlumbingRepair/PlumbingRepairDataModels/Models/IStoreModel.cs b/PlumbingRepair/PlumbingRepairDataModels/Models/IStoreModel.cs index 2d0508b..130f364 100644 --- a/PlumbingRepair/PlumbingRepairDataModels/Models/IStoreModel.cs +++ b/PlumbingRepair/PlumbingRepairDataModels/Models/IStoreModel.cs @@ -5,6 +5,7 @@ public string StoreName { get; } public string StoreAdress { get; } DateTime OpeningDate { get; } - Dictionary Works { get; } + Dictionary StoreWorks { get; } + public int WorkMaxCount { get; } } } diff --git a/PlumbingRepair/PlumbingRepairListImplement/Implements/StoreStorage.cs b/PlumbingRepair/PlumbingRepairListImplement/Implements/StoreStorage.cs index 696723f..ddb767c 100644 --- a/PlumbingRepair/PlumbingRepairListImplement/Implements/StoreStorage.cs +++ b/PlumbingRepair/PlumbingRepairListImplement/Implements/StoreStorage.cs @@ -2,6 +2,7 @@ using PlumbingRepairContracts.SearchModels; using PlumbingRepairContracts.StoragesContracts; using PlumbingRepairContracts.ViewModels; +using PlumbingRepairDataModels.Models; using PlumbingRepairListImplement.Models; namespace PlumbingRepairListImplement.Implements @@ -101,6 +102,11 @@ namespace PlumbingRepairListImplement.Implements return newStore.GetViewModel; } + public bool SellWork(IWorkModel model, int quantity) + { + throw new NotImplementedException(); + } + public StoreViewModel? Update(StoreBindingModel model) { foreach (var store in _source.Stores) diff --git a/PlumbingRepair/PlumbingRepairListImplement/Models/Store.cs b/PlumbingRepair/PlumbingRepairListImplement/Models/Store.cs index deee72e..cdd3576 100644 --- a/PlumbingRepair/PlumbingRepairListImplement/Models/Store.cs +++ b/PlumbingRepair/PlumbingRepairListImplement/Models/Store.cs @@ -13,7 +13,7 @@ namespace PlumbingRepairListImplement.Models public DateTime OpeningDate { get; private set; } - public Dictionary Works { get; private set; } = new(); + public Dictionary StoreWorks { get; private set; } = new(); public int Id { get; private set; } @@ -29,7 +29,7 @@ namespace PlumbingRepairListImplement.Models StoreName = model.StoreName, StoreAdress = model.StoreAdress, OpeningDate = model.OpeningDate, - Works = new() + StoreWorks = new() }; } @@ -42,7 +42,7 @@ namespace PlumbingRepairListImplement.Models StoreName = model.StoreName; StoreAdress = model.StoreAdress; OpeningDate = model.OpeningDate; - Works = model.Works; + StoreWorks = model.StoreWorks; } public StoreViewModel GetViewModel => new() @@ -51,7 +51,9 @@ namespace PlumbingRepairListImplement.Models StoreName = StoreName, StoreAdress = StoreAdress, OpeningDate = OpeningDate, - Works = Works + StoreWorks = StoreWorks }; + + public int WorkMaxCount => throw new NotImplementedException(); } } diff --git a/PlumbingRepair/PlumpingRepairFileImplement/DataFileSingleton.cs b/PlumbingRepair/PlumpingRepairFileImplement/DataFileSingleton.cs index 2f5e914..95b7e7d 100644 --- a/PlumbingRepair/PlumpingRepairFileImplement/DataFileSingleton.cs +++ b/PlumbingRepair/PlumpingRepairFileImplement/DataFileSingleton.cs @@ -1,5 +1,6 @@ using PlumbingRepairFileImplement.Models; using System.Xml.Linq; +using static System.Formats.Asn1.AsnWriter; namespace PlumbingRepairFileImplement { @@ -10,10 +11,12 @@ namespace PlumbingRepairFileImplement private readonly string ComponentFileName = "Component.xml"; private readonly string OrderFileName = "Order.xml"; private readonly string WorkFileName = "Work.xml"; + private readonly string StoreFileName = "Store.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Works { get; private set; } + public List Stores { get; private set; } public static DataFileSingleton GetInstance() { @@ -27,12 +30,14 @@ namespace PlumbingRepairFileImplement public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); public void SaveWorks() => SaveData(Works, WorkFileName, "Works", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); + public void SaveStores() => SaveData(Stores, StoreFileName, "Stores", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Works = LoadData(WorkFileName, "Work", x => Work.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; + Stores = LoadData(StoreFileName, "Store", x => Store.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/PlumbingRepair/PlumpingRepairFileImplement/Implements/StoreStorage.cs b/PlumbingRepair/PlumpingRepairFileImplement/Implements/StoreStorage.cs new file mode 100644 index 0000000..b1a9d58 --- /dev/null +++ b/PlumbingRepair/PlumpingRepairFileImplement/Implements/StoreStorage.cs @@ -0,0 +1,109 @@ +using PlumbingRepairContracts.BindingModels; +using PlumbingRepairContracts.SearchModels; +using PlumbingRepairContracts.StoragesContracts; +using PlumbingRepairContracts.ViewModels; +using PlumbingRepairDataModels.Models; +using PlumbingRepairFileImplement.Models; + +namespace PlumbingRepairFileImplement.Implements +{ + public class StoreStorage : IStoreStorage + { + private readonly DataFileSingleton source; + + public StoreStorage() + { + source = DataFileSingleton.GetInstance(); + } + + public StoreViewModel? GetElement(StoreSearchModel model) + { + if (string.IsNullOrEmpty(model.StoreName) && !model.Id.HasValue) + { + return null; + } + return source.Stores.FirstOrDefault(x => + (!string.IsNullOrEmpty(model.StoreName) && x.StoreName == + model.StoreName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + + public List GetFilteredList(StoreSearchModel model) + { + if (string.IsNullOrEmpty(model.StoreName)) + { + return new(); + } + return source.Stores.Where(x => + x.StoreName.Contains(model.StoreName)).Select(x => x.GetViewModel).ToList(); + } + + public List GetFullList() + { + return source.Stores.Select(x => x.GetViewModel).ToList(); + } + + public StoreViewModel? Insert(StoreBindingModel model) + { + model.Id = source.Stores.Count > 0 ? source.Stores.Max(x => x.Id) + 1 : 1; + var newStore = Store.Create(model); + if (newStore == null) + { + return null; + } + source.Stores.Add(newStore); + source.SaveStores(); + return newStore.GetViewModel; + } + + public StoreViewModel? Update(StoreBindingModel model) + { + var store = source.Stores.FirstOrDefault(x => x.Id == model.Id); + if (store == null) + { + return null; + } + store.Update(model); + source.SaveStores(); + return store.GetViewModel; + } + + public StoreViewModel? Delete(StoreBindingModel model) + { + var element = source.Stores.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + source.Stores.Remove(element); + source.SaveStores(); + return element.GetViewModel; + } + return null; + } + + public bool SellWork(IWorkModel model, int quantity) + { + if (source.Stores.Select(x => x.StoreWorks.FirstOrDefault(y => y.Key == model.Id).Value.Item2).Sum() < quantity) + { + return false; + } + foreach (var store in source.Stores.Where(x => x.StoreWorks.ContainsKey(model.Id))) + { + int QuantityInCurrentShop = store.StoreWorks[model.Id].Item2; + if (QuantityInCurrentShop <= quantity) + { + store.StoreWorks.Remove(model.Id); + quantity -= QuantityInCurrentShop; + } + else + { + store.StoreWorks[model.Id] = (store.StoreWorks[model.Id].Item1, QuantityInCurrentShop - quantity); + quantity = 0; + } + if (quantity == 0) + { + return true; + } + } + return false; + } + } +} diff --git a/PlumbingRepair/PlumpingRepairFileImplement/Models/Store.cs b/PlumbingRepair/PlumpingRepairFileImplement/Models/Store.cs new file mode 100644 index 0000000..7384d66 --- /dev/null +++ b/PlumbingRepair/PlumpingRepairFileImplement/Models/Store.cs @@ -0,0 +1,103 @@ +using PlumbingRepairContracts.BindingModels; +using PlumbingRepairContracts.ViewModels; +using PlumbingRepairDataModels.Models; +using System.Xml.Linq; + +namespace PlumbingRepairFileImplement.Models +{ + public class Store : IStoreModel + { + public string StoreName { get; private set; } = string.Empty; + public string StoreAdress { get; private set; } = string.Empty; + + public DateTime OpeningDate { get; private set; } + public Dictionary Works { get; private set; } = new(); + + public Dictionary _storeWorks = null; + + public int Id { get; private set; } + + public int WorkMaxCount { get; private set; } + + public Dictionary StoreWorks + { + get + { + if (_storeWorks == null) + { + var source = DataFileSingleton.GetInstance(); + _storeWorks = Works.ToDictionary(x => x.Key, y => ((source.Works.FirstOrDefault(z => z.Id == y.Key) as IWorkModel)!, y.Value)); + } + return _storeWorks; + } + } + + public static Store? Create(StoreBindingModel? model) + { + if (model == null) + { + return null; + } + return new Store() + { + Id = model.Id, + StoreName = model.StoreName, + StoreAdress = model.StoreAdress, + WorkMaxCount = model.WorkMaxCount, + OpeningDate = model.OpeningDate, + Works = model.StoreWorks.ToDictionary(x => x.Key, x => x.Value.Item2) + }; + } + public static Store? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + StoreName = element.Element("StoreName")!.Value, + StoreAdress = element.Element("StoreAdress")!.Value, + OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value), + WorkMaxCount = Convert.ToInt32(element.Element("WorkMaxCount")!.Value), + Works = element.Element("StoreWorks")!.Elements("Work").ToDictionary( + x => Convert.ToInt32(x.Element("Key")?.Value), + x => Convert.ToInt32(x.Element("Value")?.Value)) + }; + } + public void Update(StoreBindingModel? model) + { + if (model == null) + { + return; + } + StoreName = model.StoreName; + StoreAdress = model.StoreAdress; + OpeningDate = model.OpeningDate; + WorkMaxCount = model.WorkMaxCount; + Works = model.StoreWorks.ToDictionary(x => x.Key, x => x.Value.Item2); + _storeWorks = null; + } + public StoreViewModel GetViewModel => new() + { + Id = Id, + StoreName = StoreName, + StoreAdress = StoreAdress, + StoreWorks = StoreWorks, + OpeningDate = OpeningDate, + WorkMaxCount = WorkMaxCount, + }; + public XElement GetXElement => new("Store", + new XAttribute("Id", Id), + new XElement("StoreName", StoreName), + new XElement("StoreAdress", StoreAdress), + new XElement("OpeningDate", OpeningDate), + new XElement("WorkMaxCount", WorkMaxCount), + new XElement("StoreWorks", Works + .Select(x => new XElement("Work", + new XElement("Key", x.Key), + new XElement("Value", x.Value)) + ).ToArray())); + } +}