diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.Designer.cs index c593b65..305d5d8 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.Designer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.Designer.cs @@ -40,6 +40,7 @@ this.buttonIssuedOrder = new System.Windows.Forms.Button(); this.buttonRef = new System.Windows.Forms.Button(); this.buttonFillStore = new System.Windows.Forms.Button(); + this.buttonSellManufacture = new System.Windows.Forms.Button(); this.menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.SuspendLayout(); @@ -67,21 +68,21 @@ // componentsToolStripMenuItem // this.componentsToolStripMenuItem.Name = "componentsToolStripMenuItem"; - this.componentsToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.componentsToolStripMenuItem.Size = new System.Drawing.Size(145, 22); this.componentsToolStripMenuItem.Text = "Компоненты"; this.componentsToolStripMenuItem.Click += new System.EventHandler(this.ComponentsToolStripMenuItem_Click); // // manufacturesToolStripMenuItem // this.manufacturesToolStripMenuItem.Name = "manufacturesToolStripMenuItem"; - this.manufacturesToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.manufacturesToolStripMenuItem.Size = new System.Drawing.Size(145, 22); this.manufacturesToolStripMenuItem.Text = "Изделия"; this.manufacturesToolStripMenuItem.Click += new System.EventHandler(this.ManufacturesToolStripMenuItem_Click); // // storesToolStripMenuItem // this.storesToolStripMenuItem.Name = "storesToolStripMenuItem"; - this.storesToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.storesToolStripMenuItem.Size = new System.Drawing.Size(145, 22); this.storesToolStripMenuItem.Text = "Магазины"; this.storesToolStripMenuItem.Click += new System.EventHandler(this.StoresToolStripMenuItem_Click); // @@ -161,11 +162,22 @@ this.buttonFillStore.UseVisualStyleBackColor = true; this.buttonFillStore.Click += new System.EventHandler(this.ButtonFillStore_Click); // + // buttonSellManufacture + // + this.buttonSellManufacture.Location = new System.Drawing.Point(814, 201); + this.buttonSellManufacture.Name = "buttonSellManufacture"; + this.buttonSellManufacture.Size = new System.Drawing.Size(282, 23); + this.buttonSellManufacture.TabIndex = 3; + this.buttonSellManufacture.Text = "Продать изделие"; + this.buttonSellManufacture.UseVisualStyleBackColor = true; + this.buttonSellManufacture.Click += new System.EventHandler(this.ButtonSellManufacture_Click); + // // FormMain // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1108, 504); + this.Controls.Add(this.buttonSellManufacture); this.Controls.Add(this.buttonFillStore); this.Controls.Add(this.buttonRef); this.Controls.Add(this.buttonIssuedOrder); @@ -200,5 +212,6 @@ private Button buttonRef; private ToolStripMenuItem storesToolStripMenuItem; private Button buttonFillStore; + private Button buttonSellManufacture; } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.cs index 2b86baf..9206973 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.cs @@ -162,5 +162,13 @@ namespace BlacksmithWorkshopView form.ShowDialog(); } } + private void ButtonSellManufacture_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSellManufacture)); + if (service is FormSellManufacture form) + { + form.ShowDialog(); + } + } } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormSellManufacture.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormSellManufacture.Designer.cs new file mode 100644 index 0000000..b5e000f --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormSellManufacture.Designer.cs @@ -0,0 +1,121 @@ +namespace BlacksmithWorkshopView +{ + partial class FormSellManufacture + { + /// + /// 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.buttonCancel = new System.Windows.Forms.Button(); + this.buttonSell = new System.Windows.Forms.Button(); + this.labelCount = new System.Windows.Forms.Label(); + this.labelManufacture = new System.Windows.Forms.Label(); + this.textBoxCount = new System.Windows.Forms.TextBox(); + this.comboBoxManufacture = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(256, 70); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 23); + this.buttonCancel.TabIndex = 15; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // buttonSell + // + this.buttonSell.Location = new System.Drawing.Point(175, 70); + this.buttonSell.Name = "buttonSell"; + this.buttonSell.Size = new System.Drawing.Size(75, 23); + this.buttonSell.TabIndex = 16; + this.buttonSell.Text = "Продать"; + this.buttonSell.UseVisualStyleBackColor = true; + this.buttonSell.Click += new System.EventHandler(this.ButtonSell_Click); + // + // labelCount + // + this.labelCount.AutoSize = true; + this.labelCount.Location = new System.Drawing.Point(12, 44); + this.labelCount.Name = "labelCount"; + this.labelCount.Size = new System.Drawing.Size(72, 15); + this.labelCount.TabIndex = 13; + this.labelCount.Text = "Количество"; + // + // labelManufacture + // + this.labelManufacture.AutoSize = true; + this.labelManufacture.Location = new System.Drawing.Point(12, 15); + this.labelManufacture.Name = "labelManufacture"; + this.labelManufacture.Size = new System.Drawing.Size(53, 15); + this.labelManufacture.TabIndex = 14; + this.labelManufacture.Text = "Изделие"; + // + // textBoxCount + // + this.textBoxCount.Location = new System.Drawing.Point(107, 41); + this.textBoxCount.Name = "textBoxCount"; + this.textBoxCount.Size = new System.Drawing.Size(224, 23); + this.textBoxCount.TabIndex = 12; + // + // comboBoxManufacture + // + this.comboBoxManufacture.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBoxManufacture.FormattingEnabled = true; + this.comboBoxManufacture.Location = new System.Drawing.Point(107, 12); + this.comboBoxManufacture.Name = "comboBoxManufacture"; + this.comboBoxManufacture.Size = new System.Drawing.Size(224, 23); + this.comboBoxManufacture.TabIndex = 11; + // + // FormSellManufacture + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(347, 107); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonSell); + this.Controls.Add(this.labelCount); + this.Controls.Add(this.labelManufacture); + this.Controls.Add(this.textBoxCount); + this.Controls.Add(this.comboBoxManufacture); + this.Name = "FormSellManufacture"; + this.Text = "Продажа изделия"; + this.Load += new System.EventHandler(this.FormFillStore_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Button buttonCancel; + private Button buttonSell; + private Label labelCount; + private Label labelManufacture; + private TextBox textBoxCount; + private ComboBox comboBoxManufacture; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormSellManufacture.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormSellManufacture.cs new file mode 100644 index 0000000..50c89a8 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormSellManufacture.cs @@ -0,0 +1,65 @@ +using BlacksmithWorkshopContracts.BusinessLogicContracts; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace BlacksmithWorkshopView +{ + public partial class FormSellManufacture : Form + { + private readonly ILogger _logger; + private readonly IStoreLogic _logicS; + private readonly IManufactureLogic _logicM; + public FormSellManufacture(ILogger logger, IStoreLogic logicS, IManufactureLogic logicM) + { + InitializeComponent(); + _logger = logger; + _logicS = logicS; + _logicM = logicM; + } + private void FormFillStore_Load(object sender, EventArgs e) + { + _logger.LogInformation("Загрузка изделий"); + var listM = _logicM.ReadList(null); + if (listM != null) + { + comboBoxManufacture.DisplayMember = "ManufactureName"; + comboBoxManufacture.ValueMember = "Id"; + comboBoxManufacture.DataSource = listM; + comboBoxManufacture.SelectedItem = null; + } + } + private void ButtonSell_Click(object sender, EventArgs e) + { + if (comboBoxManufacture.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (Convert.ToInt32(textBoxCount.Text) <= 0) + { + MessageBox.Show("Количество должно быть больше нуля", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + var count = Convert.ToInt32(textBoxCount.Text); + var manufacture = _logicM.ReadElement(new() + { + Id = Convert.ToInt32(comboBoxManufacture.SelectedValue) + }); + if (manufacture == null || !_logicS.SellManufactures(manufacture, count)) + { + 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/BlacksmithWorkshop/BlacksmithWorkshop/FormSellManufacture.resx b/BlacksmithWorkshop/BlacksmithWorkshop/FormSellManufacture.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormSellManufacture.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/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs b/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs index f025d7e..f0c2952 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs @@ -51,6 +51,7 @@ namespace BlacksmithWorkshopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs index 007c1c7..d0ff0fd 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,5 +1,6 @@ using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicContracts; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; using BlacksmithWorkshopContracts.SearchModels; using BlacksmithWorkshopContracts.StoragesContracts; using BlacksmithWorkshopContracts.ViewModels; @@ -12,10 +13,14 @@ namespace BlacksmithWorkShopBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + private readonly IManufactureStorage _manufactureStorage; + private readonly IStoreLogic _storeLogic; + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IManufactureStorage manufactureStorage, IStoreLogic storeLogic) { _logger = logger; _orderStorage = orderStorage; + _manufactureStorage = manufactureStorage; + _storeLogic = storeLogic; } public List? ReadList(OrderSearchModel? model) { @@ -48,7 +53,22 @@ namespace BlacksmithWorkShopBusinessLogic.BusinessLogics { return true; } - } + if (newstatus == OrderStatus.Выдан) + { + if (vm == null) + { + return false; + } + var manufacture = _manufactureStorage.GetElement(new ManufactureSearchModel + { + Id = vm.ManufactureId + }); + if (manufacture == null || !_storeLogic.FillStore(manufacture, vm.Count)) + { + throw new Exception("Не удалось заполнить магазины"); + } + } + } _logger.LogWarning($"Changing order status of order {model.Id} to {newstatus} failed"); return false; } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/StoreLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/StoreLogic.cs index 1024bc3..cdea605 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/StoreLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/StoreLogic.cs @@ -142,7 +142,7 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics throw new ArgumentNullException("Нет адреса магазина", nameof(model.StoreName)); } _logger.LogInformation("Store. StoreName: {StoreName}. Address: {Address}. Id: {Id}", model.StoreName, model.Address, model.Id); - var element = _storeStorage.GetElement(new StoreSearchModel//проверка на уникальность + var element = _storeStorage.GetElement(new StoreSearchModel { StoreName = model.StoreName }); @@ -150,6 +150,59 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics { throw new InvalidOperationException("Магазин с таким названием уже есть"); } + if (model.MaxManufactures <= 0) + { + throw new ArgumentException("Максимальное количество изделий не может быть меньше единицы", nameof(model.MaxManufactures)); + } + } + public int GetFreePlace(int count) + { + int result; + var stores = _storeStorage.GetFullList(); + result = stores//Получаем общее число свободных мест в магазине + .Select(x => x.MaxManufactures/*максимальное число мест в магазине*/ - x.Manufactures.Select(m => m.Value.Item2).Sum()).Sum()/*количество занятых мест до добавления изделия*/; + result -= count;//Получаем общее число свободных мест после добавления изделия + return result; + } + public bool FillStore(IManufactureModel manufacture, int count) + { + if (count <= 0) + { + _logger.LogWarning("Количество добавляемых изделий должно быть больше 0."); + return false; + } + var freePlaces = GetFreePlace(count); + if (freePlaces < 0) + { + _logger.LogInformation("Магазины переполнены."); + return false; + } + foreach (var store in _storeStorage.GetFullList())//добавляем изделие во все магазины + { + var cnt = Math.Min(count, store.MaxManufactures - store.Manufactures.Select(x => x.Value.Item2).Sum()); + if (cnt <= 0) + { + continue; + } + if (!AddManufacture(manufacture, new StoreSearchModel() + { + Id = store.Id + }, cnt)) + { + _logger.LogWarning("При добавлении изделий произошла ошибка"); + return false; + } + count -= cnt; + if (count == 0) + { + return true; + } + } + return true; + } + public bool SellManufactures(IManufactureModel manufacture, int count) + { + return _storeStorage.SellManufacture(manufacture, count); } } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/StoreBindingModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/StoreBindingModel.cs index 054387c..0039b55 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/StoreBindingModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/StoreBindingModel.cs @@ -12,5 +12,6 @@ namespace BlacksmithWorkshopContracts.BindingModels /// Изделия в магазине /// public Dictionary Manufactures { get; set; } = new(); + public int MaxManufactures { get; set; } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IStoreLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IStoreLogic.cs index d0941d2..63d3cc8 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IStoreLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IStoreLogic.cs @@ -20,5 +20,8 @@ namespace BlacksmithWorkshopContracts.BusinessLogicsContracts /// Количество изделий /// bool AddManufacture(IManufactureModel manufacture, StoreSearchModel model, int count); + int GetFreePlace(int count); + bool FillStore(IManufactureModel manufacture, int count); + public bool SellManufactures(IManufactureModel manufacture, int needCount); } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IStoreStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IStoreStorage.cs index 2eab6c8..d8502eb 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IStoreStorage.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StoragesContracts/IStoreStorage.cs @@ -13,5 +13,19 @@ namespace BlacksmithWorkshopContracts.StoragesContracts StoreViewModel? Insert(StoreBindingModel model); StoreViewModel? Update(StoreBindingModel model); StoreViewModel? Delete(StoreBindingModel model); + /// + /// Проверка наличия изделия в нужном количестве + /// + /// Изделие + /// Количество + /// + bool HasManufactures(IManufactureModel manufacture, int count); + /// + /// Продажа изделия в нужном количестве + /// + /// Изделие + /// Количество + /// + bool SellManufacture(IManufactureModel manufacture, int count); } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/StoreViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/StoreViewModel.cs index b7675d2..c92c958 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/StoreViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/StoreViewModel.cs @@ -17,5 +17,7 @@ namespace BlacksmithWorkshopContracts.ViewModels /// Изделия в магазине /// public Dictionary Manufactures { get; set; } = new(); + [DisplayName("Макс. изделий")] + public int MaxManufactures { get; set; } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IStoreModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IStoreModel.cs index cf653ec..124ab1c 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IStoreModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IStoreModel.cs @@ -6,5 +6,6 @@ string Address { get; } DateTime OpeningDate { get; } Dictionary Manufactures { get; } + int MaxManufactures { get; } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/DataFileSingleton.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/DataFileSingleton.cs index a2b8f6c..a59ca30 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/DataFileSingleton.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/DataFileSingleton.cs @@ -8,9 +8,11 @@ namespace BlacksmithWorkshopFileImplement private readonly string ComponentFileName = "Component.xml"; private readonly string OrderFileName = "Order.xml"; private readonly string ManufactureFileName = "Manufacture.xml"; + private readonly string StoreFileName = "Store.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Manufactures { get; private set; } + public List Stores { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -22,11 +24,13 @@ namespace BlacksmithWorkshopFileImplement public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); public void SaveManufactures() => SaveData(Manufactures, ManufactureFileName, "Manufactures", 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)!)!; Manufactures = LoadData(ManufactureFileName, "Manufacture", x => Manufacture.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/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/StoreStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/StoreStorage.cs new file mode 100644 index 0000000..192f3ac --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/StoreStorage.cs @@ -0,0 +1,117 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Models; +using BlacksmithWorkshopFileImplement.Models; + +namespace BlacksmithWorkshopFileImplement.Implements +{ + public class StoreStorage : IStoreStorage + { + private readonly DataFileSingleton source; + public StoreStorage() + { + source = DataFileSingleton.GetInstance(); + } + public List GetFullList() + { + return source.Stores + .Select(x => x.GetViewModel) + .ToList(); + } + public List GetFilteredList(StoreSearchModel model) + { + if (model.Id.HasValue)//сначала ищем по Id + { + return source.Stores + .Where(x => x.Id == model.Id) + .Select(x => x.GetViewModel) + .ToList(); + } + else if (!string.IsNullOrEmpty(model.StoreName))//далее по названию магазина + { + return source.Stores + .Where(x => x.StoreName.Contains(model.StoreName)) + .Select(x => x.GetViewModel) + .ToList(); + } + return new(); + } + public StoreViewModel? GetElement(StoreSearchModel model) + { + if (model.Id.HasValue)//сначала ищем по Id + { + return source.Stores + .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + } + else if (!string.IsNullOrEmpty(model.StoreName))//далее по названию магазина + { + return source.Stores + .FirstOrDefault(x => x.StoreName.Contains(model.StoreName))?.GetViewModel; + } + return null; + } + 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.StoreName == model.StoreName); + 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 HasManufactures(IManufactureModel manufacture, int count) + { + var currentCount = source.Stores + .Select(x => x.Manufactures + .FirstOrDefault(x => x.Key == manufacture.Id).Value.Item2) + .Sum(); + return currentCount >= count; + } + public bool SellManufacture(IManufactureModel manufacture, int count) + { + if (!HasManufactures(manufacture, count)) + { + return false; + } + foreach (var store in source.Stores.Where(x => x.Manufactures.ContainsKey(manufacture.Id))) + { + var difference = Math.Min(store.Manufactures[manufacture.Id].Item2, count); + store.Manufactures[manufacture.Id] = (store.Manufactures[manufacture.Id].Item1, store.Manufactures[manufacture.Id].Item2 - difference); + + count -= difference; + if (count <= 0) + { + return true; + } + } + return true; + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Store.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Store.cs new file mode 100644 index 0000000..4399b77 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Store.cs @@ -0,0 +1,108 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.ViewModels; +using BlacksmithWorkshopDataModels.Models; +using System.Diagnostics; +using System.Xml.Linq; + +namespace BlacksmithWorkshopFileImplement.Models +{ + public class Store : IStoreModel + { + public int Id { get; private set; } + public string StoreName { get; private set; } = string.Empty; + public string Address { get; private set; } = string.Empty; + public DateTime OpeningDate { get; private set; } = DateTime.Now; + public Dictionary SavedManufactures { get; private set; } = new(); + private Dictionary? _manufactures = null; + public Dictionary Manufactures + { + get + { + if (_manufactures == null) + { + var source = DataFileSingleton.GetInstance(); + _manufactures = SavedManufactures.ToDictionary(x => x.Key, y => + ((source.Manufactures.FirstOrDefault(z => z.Id == y.Key) as IManufactureModel)!, + y.Value)); + } + return _manufactures; + } + } + public int MaxManufactures { get; private set; } + public static Store? Create(StoreBindingModel model) + { + if (model == null) + { + return null; + } + return new Store() + { + Id = model.Id, + StoreName = model.StoreName, + Address = model.Address, + OpeningDate = model.OpeningDate, + SavedManufactures = model.Manufactures.ToDictionary(x => x.Value.Item1.Id, x => x.Value.Item2), + MaxManufactures = model.MaxManufactures, + }; + } + public static Store? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Store() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + StoreName = element.Element("StoreName")!.Value, + Address = element.Element("Address")!.Value, + OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value), + SavedManufactures = element.Element("Manufactures")!.Elements("Manufacture").ToDictionary + ( + x => Convert.ToInt32(x.Element("Key")?.Value), + x => Convert.ToInt32(x.Element("Value")?.Value) + ), + MaxManufactures = Convert.ToInt32(element.Element("MaxManufactures")!.Value) + }; + } + public void Update(StoreBindingModel model) + { + if (model == null) + { + return; + } + StoreName = model.StoreName; + Address = model.Address; + OpeningDate= model.OpeningDate; + SavedManufactures = model.Manufactures.ToDictionary(x => x.Value.Item1.Id, x => x.Value.Item2); + _manufactures = null; + MaxManufactures = model.MaxManufactures; + } + public StoreViewModel GetViewModel => new() + { + Id = Id, + StoreName = StoreName, + Address = Address, + OpeningDate = OpeningDate, + Manufactures = Manufactures, + MaxManufactures = MaxManufactures + }; + public XElement GetXElement => new + ( + "Store", + new XAttribute("Id", Id), + new XElement("StoreName", StoreName), + new XElement("Address", Address), + new XElement("OpeningDate", OpeningDate), + new XElement("Manufactures", SavedManufactures.Select + (x => new XElement + ( + "Manufacture", + new XElement("Key", x.Key), + new XElement("Value", x.Value) + ) + ).ToArray()), + new XElement("MaxManufactures", MaxManufactures) + ); + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/StoreStorage.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/StoreStorage.cs index 3fb8c5d..1fd4c2e 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/StoreStorage.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Implements/StoreStorage.cs @@ -100,5 +100,13 @@ namespace BlacksmithWorkshopListImplement.Implements } return null; } + public bool HasManufactures(IManufactureModel manufacture, int count) + { + throw new NotImplementedException("Не применяется в данной реализации"); + } + public bool SellManufacture(IManufactureModel manufacture, int count) + { + throw new NotImplementedException("Не применяется в данной реализации"); + } } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Store.cs b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Store.cs index 28ce5d2..7060570 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Store.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopListImplement/Models/Store.cs @@ -11,6 +11,7 @@ namespace BlacksmithWorkshopListImplement.Models public string Address { get; private set; } = string.Empty; public DateTime OpeningDate { get; private set; } public Dictionary Manufactures { get; private set; } = new(); + public int MaxManufactures { get; private set; } public static Store? Create(StoreBindingModel? model) { if (model == null) @@ -23,7 +24,8 @@ namespace BlacksmithWorkshopListImplement.Models StoreName = model.StoreName, Address = model.Address, OpeningDate = model.OpeningDate, - Manufactures = new() + Manufactures = new(), + MaxManufactures = model.MaxManufactures }; } public void Update(StoreBindingModel? model) @@ -36,6 +38,7 @@ namespace BlacksmithWorkshopListImplement.Models Address = model.Address; OpeningDate = model.OpeningDate; Manufactures = model.Manufactures; + MaxManufactures = model.MaxManufactures; } public StoreViewModel GetViewModel => new() { @@ -43,7 +46,8 @@ namespace BlacksmithWorkshopListImplement.Models StoreName = StoreName, Address = Address, OpeningDate = OpeningDate, - Manufactures = Manufactures + Manufactures = Manufactures, + MaxManufactures = MaxManufactures }; } }