Hard LabWork02 (Вроде работает)

This commit is contained in:
Павел Сорокин 2023-03-05 17:02:24 +04:00
parent 730f100af9
commit bf9de0295a
21 changed files with 683 additions and 35 deletions

View File

@ -40,6 +40,7 @@
this.магазинToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ButtonAddShip = new System.Windows.Forms.Button();
this.ButtonSellShip = new System.Windows.Forms.Button();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
@ -123,21 +124,21 @@
// ДеталиToolStripMenuItem
//
this.ДеталиToolStripMenuItem.Name = еталиToolStripMenuItem";
this.ДеталиToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.ДеталиToolStripMenuItem.Size = new System.Drawing.Size(163, 26);
this.ДеталиToolStripMenuItem.Text = "Детали";
this.ДеталиToolStripMenuItem.Click += new System.EventHandler(this.ДеталиToolStripMenuItem_Click);
//
// КораблиToolStripMenuItem
//
this.КораблиToolStripMenuItem.Name = "КораблиToolStripMenuItem";
this.КораблиToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.КораблиToolStripMenuItem.Size = new System.Drawing.Size(163, 26);
this.КораблиToolStripMenuItem.Text = "Корабли";
this.КораблиToolStripMenuItem.Click += new System.EventHandler(this.КораблиToolStripMenuItem_Click);
//
// магазинToolStripMenuItem
//
this.магазинToolStripMenuItem.Name = агазинToolStripMenuItem";
this.магазинToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.магазинToolStripMenuItem.Size = new System.Drawing.Size(163, 26);
this.магазинToolStripMenuItem.Text = "Магазины";
this.магазинToolStripMenuItem.Click += new System.EventHandler(this.МагазиныToolStripMenuItem_Click);
//
@ -162,11 +163,22 @@
this.ButtonAddShip.UseVisualStyleBackColor = true;
this.ButtonAddShip.Click += new System.EventHandler(this.ButtonAddShip_Click);
//
// ButtonSellShip
//
this.ButtonSellShip.Location = new System.Drawing.Point(961, 433);
this.ButtonSellShip.Name = "ButtonSellShip";
this.ButtonSellShip.Size = new System.Drawing.Size(187, 29);
this.ButtonSellShip.TabIndex = 8;
this.ButtonSellShip.Text = "Продать корабль";
this.ButtonSellShip.UseVisualStyleBackColor = true;
this.ButtonSellShip.Click += new System.EventHandler(this.ButtonSellShip_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1160, 474);
this.Controls.Add(this.ButtonSellShip);
this.Controls.Add(this.ButtonAddShip);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.ButtonRef);
@ -201,5 +213,6 @@
private DataGridView dataGridView;
private ToolStripMenuItem магазинToolStripMenuItem;
private Button ButtonAddShip;
private Button ButtonSellShip;
}
}

View File

@ -173,5 +173,15 @@ namespace ShipyardView
LoadData();
}
}
private void ButtonSellShip_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSellShips));
if (service is FormSellShips form)
{
form.ShowDialog();
LoadData();
}
}
}
}

View File

@ -0,0 +1,120 @@
namespace ShipyardView
{
partial class FormSellShips
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.ButtonCancel = new System.Windows.Forms.Button();
this.comboBoxShips = new System.Windows.Forms.ComboBox();
this.numericUpDownCount = new System.Windows.Forms.NumericUpDown();
this.labelShip = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.ButtonSave = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).BeginInit();
this.SuspendLayout();
//
// ButtonCancel
//
this.ButtonCancel.Location = new System.Drawing.Point(266, 153);
this.ButtonCancel.Name = "ButtonCancel";
this.ButtonCancel.Size = new System.Drawing.Size(94, 29);
this.ButtonCancel.TabIndex = 1;
this.ButtonCancel.Text = "Отмена";
this.ButtonCancel.UseVisualStyleBackColor = true;
this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// comboBoxShips
//
this.comboBoxShips.FormattingEnabled = true;
this.comboBoxShips.Location = new System.Drawing.Point(144, 38);
this.comboBoxShips.Name = "comboBoxShips";
this.comboBoxShips.Size = new System.Drawing.Size(216, 28);
this.comboBoxShips.TabIndex = 2;
//
// numericUpDownCount
//
this.numericUpDownCount.Location = new System.Drawing.Point(144, 102);
this.numericUpDownCount.Name = "numericUpDownCount";
this.numericUpDownCount.Size = new System.Drawing.Size(216, 27);
this.numericUpDownCount.TabIndex = 3;
//
// labelShip
//
this.labelShip.AutoSize = true;
this.labelShip.Location = new System.Drawing.Point(34, 38);
this.labelShip.Name = "labelShip";
this.labelShip.Size = new System.Drawing.Size(69, 20);
this.labelShip.TabIndex = 4;
this.labelShip.Text = "Корабль";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(34, 109);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(90, 20);
this.labelCount.TabIndex = 5;
this.labelCount.Text = "Количество";
//
// ButtonSave
//
this.ButtonSave.Location = new System.Drawing.Point(144, 153);
this.ButtonSave.Name = "ButtonSave";
this.ButtonSave.Size = new System.Drawing.Size(94, 29);
this.ButtonSave.TabIndex = 6;
this.ButtonSave.Text = "Сохранить";
this.ButtonSave.UseVisualStyleBackColor = true;
this.ButtonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// FormSellShips
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(373, 194);
this.Controls.Add(this.ButtonSave);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelShip);
this.Controls.Add(this.numericUpDownCount);
this.Controls.Add(this.comboBoxShips);
this.Controls.Add(this.ButtonCancel);
this.Name = "FormSellShips";
this.Text = "Продажа кораблей";
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button ButtonCancel;
private ComboBox comboBoxShips;
private NumericUpDown numericUpDownCount;
private Label labelShip;
private Label labelCount;
private Button ButtonSave;
}
}

View File

@ -0,0 +1,86 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.ViewModels;
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 ShipyardView
{
public partial class FormSellShips : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _shopLogic;
private readonly IShipLogic _shipLogic;
private readonly List<ShipViewModel>? _listShip;
public FormSellShips(ILogger<FormSellShips> logger, IShopLogic shopLogic, IShipLogic shipLogic)
{
InitializeComponent();
_logger = logger;
_shopLogic = shopLogic;
_shipLogic = shipLogic;
_listShip = shipLogic.ReadList(null);
if (_listShip != null)
{
comboBoxShips.DisplayMember = "ShipName";
comboBoxShips.ValueMember = "Id";
comboBoxShips.DataSource=_listShip;
comboBoxShips.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (comboBoxShips.SelectedValue == null)
{
MessageBox.Show("Выберите корабль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(numericUpDownCount.Text))
{
MessageBox.Show("Заполните количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Продажа поездок");
try
{
var ship = _shipLogic.ReadElement(new()
{
Id = (int)comboBoxShips.SelectedValue
});
if (ship == null)
{
throw new Exception("Корабль не найден. Дополнительная информация в логах.");
}
var operationResult = _shopLogic.SellShips(
model: ship,
count: (int)numericUpDownCount.Value
);
if (!operationResult)
{
throw new Exception("Ошибка при продаже корабля. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения корабля");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

View File

@ -35,12 +35,15 @@
this.textBoxAddress = new System.Windows.Forms.TextBox();
this.dateTimePickerDateOpen = new System.Windows.Forms.DateTimePicker();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ButtonSave = new System.Windows.Forms.Button();
this.ButtonCancel = new System.Windows.Forms.Button();
this.ID = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ShipName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ButtonSave = new System.Windows.Forms.Button();
this.ButtonCancel = new System.Windows.Forms.Button();
this.numericUpDownCapacity = new System.Windows.Forms.NumericUpDown();
this.labelCapacity = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCapacity)).BeginInit();
this.SuspendLayout();
//
// labelShop
@ -64,7 +67,7 @@
// labelDate
//
this.labelDate.AutoSize = true;
this.labelDate.Location = new System.Drawing.Point(474, 21);
this.labelDate.Location = new System.Drawing.Point(386, 21);
this.labelDate.Name = "labelDate";
this.labelDate.Size = new System.Drawing.Size(110, 20);
this.labelDate.TabIndex = 2;
@ -81,14 +84,14 @@
//
this.textBoxAddress.Location = new System.Drawing.Point(195, 44);
this.textBoxAddress.Name = "textBoxAddress";
this.textBoxAddress.Size = new System.Drawing.Size(246, 27);
this.textBoxAddress.Size = new System.Drawing.Size(159, 27);
this.textBoxAddress.TabIndex = 4;
//
// dateTimePickerDateOpen
//
this.dateTimePickerDateOpen.Location = new System.Drawing.Point(474, 44);
this.dateTimePickerDateOpen.Location = new System.Drawing.Point(386, 44);
this.dateTimePickerDateOpen.Name = "dateTimePickerDateOpen";
this.dateTimePickerDateOpen.Size = new System.Drawing.Size(250, 27);
this.dateTimePickerDateOpen.Size = new System.Drawing.Size(185, 27);
this.dateTimePickerDateOpen.TabIndex = 5;
//
// dataGridView
@ -105,26 +108,6 @@
this.dataGridView.Size = new System.Drawing.Size(712, 330);
this.dataGridView.TabIndex = 6;
//
// ButtonSave
//
this.ButtonSave.Location = new System.Drawing.Point(490, 413);
this.ButtonSave.Name = "ButtonSave";
this.ButtonSave.Size = new System.Drawing.Size(111, 29);
this.ButtonSave.TabIndex = 7;
this.ButtonSave.Text = "Сохранить";
this.ButtonSave.UseVisualStyleBackColor = true;
this.ButtonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// ButtonCancel
//
this.ButtonCancel.Location = new System.Drawing.Point(630, 413);
this.ButtonCancel.Name = "ButtonCancel";
this.ButtonCancel.Size = new System.Drawing.Size(94, 29);
this.ButtonCancel.TabIndex = 8;
this.ButtonCancel.Text = "Отмена";
this.ButtonCancel.UseVisualStyleBackColor = true;
this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// ID
//
this.ID.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
@ -147,11 +130,49 @@
this.Count.MinimumWidth = 6;
this.Count.Name = "Count";
//
// ButtonSave
//
this.ButtonSave.Location = new System.Drawing.Point(490, 413);
this.ButtonSave.Name = "ButtonSave";
this.ButtonSave.Size = new System.Drawing.Size(111, 29);
this.ButtonSave.TabIndex = 7;
this.ButtonSave.Text = "Сохранить";
this.ButtonSave.UseVisualStyleBackColor = true;
this.ButtonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// ButtonCancel
//
this.ButtonCancel.Location = new System.Drawing.Point(630, 413);
this.ButtonCancel.Name = "ButtonCancel";
this.ButtonCancel.Size = new System.Drawing.Size(94, 29);
this.ButtonCancel.TabIndex = 8;
this.ButtonCancel.Text = "Отмена";
this.ButtonCancel.UseVisualStyleBackColor = true;
this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// numericUpDownCapacity
//
this.numericUpDownCapacity.Location = new System.Drawing.Point(594, 44);
this.numericUpDownCapacity.Name = "numericUpDownCapacity";
this.numericUpDownCapacity.Size = new System.Drawing.Size(117, 27);
this.numericUpDownCapacity.TabIndex = 9;
//
// labelCapacity
//
this.labelCapacity.AutoSize = true;
this.labelCapacity.Location = new System.Drawing.Point(594, 21);
this.labelCapacity.Name = "labelCapacity";
this.labelCapacity.Size = new System.Drawing.Size(100, 20);
this.labelCapacity.TabIndex = 10;
this.labelCapacity.Text = "Вместимость";
//
// FormShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(740, 450);
this.Controls.Add(this.labelCapacity);
this.Controls.Add(this.numericUpDownCapacity);
this.Controls.Add(this.ButtonCancel);
this.Controls.Add(this.ButtonSave);
this.Controls.Add(this.dataGridView);
@ -165,6 +186,7 @@
this.Text = "Магазин";
this.Load += new System.EventHandler(this.FormShop_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCapacity)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
@ -184,5 +206,7 @@
private DataGridViewTextBoxColumn ID;
private DataGridViewTextBoxColumn ShipName;
private DataGridViewTextBoxColumn Count;
private NumericUpDown numericUpDownCapacity;
private Label labelCapacity;
}
}

View File

@ -47,6 +47,7 @@ namespace ShipyardView
textBoxName.Text = view.ShopName;
textBoxAddress.Text = view.Address.ToString();
dateTimePickerDateOpen.Text = view.DateOpen.ToString();
numericUpDownCapacity.Value=view.Capacity;
_shopShips = view.Ships ?? new Dictionary<int, (IShipModel, int)>();
LoadData();
}
@ -96,6 +97,11 @@ namespace ShipyardView
MessageBox.Show("Заполните дату", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (numericUpDownCapacity.Value <= 0)
{
MessageBox.Show("Вместимость должна быть больше нуля", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение магазина");
try
{
@ -104,7 +110,9 @@ namespace ShipyardView
Id = _id ?? 0,
ShopName = textBoxName.Text,
Address = textBoxAddress.Text,
DateOpen = DateTime.Parse(dateTimePickerDateOpen.Text)
DateOpen = DateTime.Parse(dateTimePickerDateOpen.Text),
Capacity = (int)numericUpDownCapacity.Value,
Ships = _shopShips
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)

View File

@ -66,4 +66,13 @@
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ID.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ShipName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -54,6 +54,7 @@ namespace ShipyardView
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormAddShip>();
services.AddTransient<FormSellShips>();
}
}

View File

@ -7,6 +7,7 @@ using ShipyardContracts.ViewModels;
using ShipyardDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -17,10 +18,14 @@ namespace ShipyardBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
private readonly IShopLogic _shopLogic;
private readonly IShipStorage _shipStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopLogic shopLogic,IShipStorage shipStorage)
{
_logger = logger;
_orderStorage = orderStorage;
_shopLogic = shopLogic;
_shipStorage = shipStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
@ -83,7 +88,19 @@ namespace ShipyardBusinessLogic.BusinessLogics
return false;
}
model.Status = newStatus;
if (model.Status == OrderStatus.Готов) model.DateImplement = DateTime.Now;
if (model.Status == OrderStatus.Готов)
{
model.DateImplement = DateTime.Now;
var ship = _shipStorage.GetElement(new() { Id = viewModel.ShipId });
if (ship == null)
{
throw new ArgumentNullException(nameof(ship));
}
if (!_shopLogic.AddShips(ship, viewModel.Count))
{
throw new Exception($"AddShips operation failed");
}
}
else
{
model.DateImplement = viewModel.DateImplement;

View File

@ -7,6 +7,7 @@ using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -115,7 +116,7 @@ namespace ShipyardBusinessLogic.BusinessLogics
}
if (count <= 0)
{
throw new ArgumentException("Количество поездок должно быть больше 0", nameof(count));
throw new ArgumentException("Количество кораблей должно быть больше 0", nameof(count));
}
_logger.LogInformation("AddShip. ShopName:{ShopName}. Id:{Id}", model.ShopName, model.Id);
var element = _shopStorage.GetElement(model);
@ -124,8 +125,10 @@ namespace ShipyardBusinessLogic.BusinessLogics
_logger.LogWarning("AddShip element not found");
return false;
}
_logger.LogInformation("AddShip find. Id:{Id}", element.Id);
if (element.Capacity - element.Ships.FirstOrDefault(x => x.Key == ship.Id).Value.Item2 < count)
{
throw new ArgumentNullException("В магазине не хватает места", nameof(count));
}
if (element.Ships.TryGetValue(ship.Id, out var pair))
{
element.Ships[ship.Id] = (ship, count + pair.Item2);
@ -144,9 +147,54 @@ namespace ShipyardBusinessLogic.BusinessLogics
Address = element.Address,
ShopName = element.ShopName,
DateOpen = element.DateOpen,
Capacity = element.Capacity,
Ships = element.Ships
});
return true;
}
public bool AddShips(IShipModel model, int count)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (count <= 0)
{
throw new ArgumentException("Количество кораблей должно быть больше 0", nameof(count));
}
_logger.LogInformation("AddShips. ShopName:{ShopName}. Id:{Id}", model.ShipName, model.Id);
foreach (var shop in _shopStorage.GetFullList())
{
int freeQuantity = shop.Capacity - shop.Ships.Select(x => x.Value.Item2).Sum();
if (freeQuantity < count)
{
if (!AddShip(new() { Id = shop.Id }, model, freeQuantity))
{
_logger.LogWarning("AddShips operation failed.");
return false;
}
count -= freeQuantity;
}
else
{
if (!AddShip(new() { Id = shop.Id }, model, count))
{
_logger.LogWarning("AddShips operation failed.");
return false;
}
count = 0;
}
if (count == 0)
{
return true;
}
}
_logger.LogWarning("AddShips operation failed.");
return false;
}
public bool SellShips(IShipModel model, int count)
{
return _shopStorage.SellShips(model, count);
}
}
}

View File

@ -12,6 +12,7 @@ namespace ShipyardContracts.BindingModels
public string ShopName { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public DateTime DateOpen { get; set; } = DateTime.Now;
public int Capacity { get; set; }
public Dictionary<int, (IShipModel, int)> Ships { get; set; } = new();
public int Id { get; set; }
}

View File

@ -18,5 +18,7 @@ namespace ShipyardContracts.BusinessLogicsContracts
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool AddShip(ShopSearchModel model, IShipModel ship, int count);
bool AddShips (IShipModel model,int count);
bool SellShips(IShipModel model,int count);
}
}

View File

@ -1,6 +1,7 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
@ -17,5 +18,7 @@ namespace ShipyardContracts.StoragesContracts
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool ShipsAreAvailable(IShipModel model, int requiredQuantity);
bool SellShips(IShipModel model, int count);
}
}

View File

@ -18,6 +18,8 @@ namespace ShipyardContracts.ViewModels
[DisplayName("Дата открытия")]
public DateTime DateOpen { get; set; } = DateTime.Now;
[DisplayName("Вместимость магазина")]
public int Capacity { get; set; }
public Dictionary<int, (IShipModel, int)> Ships { get; set; } = new();
public int Id { get; set; }
}

View File

@ -11,6 +11,7 @@ namespace ShipyardDataModels.Models
string ShopName { get; }
string Address { get; }
DateTime DateOpen { get; }
public int Capacity { get; }
Dictionary<int, (IShipModel, int)> Ships { get; }
}
}

View File

@ -15,9 +15,11 @@ namespace ShipyardFileImplement
private readonly string DetailFileName = "Detail.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string ShipFileName = "Ship.xml";
private readonly string ShopFileName = "Shop.xml";
public List<Detail> Details { get; private set; }
public List<Order> Orders { get; private set; }
public List<Ship> Ships { get; private set; }
public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -29,11 +31,13 @@ namespace ShipyardFileImplement
public void SaveDetails() => SaveData(Details, DetailFileName,"Details", x => x.GetXElement);
public void SaveShips() => SaveData(Ships, ShipFileName,"Ships", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x=> x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
private DataFileSingleton()
{
Details = LoadData(DetailFileName, "Detail", x => Detail.Create(x)!)!;
Ships = LoadData(ShipFileName, "Ship", x => Ship.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)

View File

@ -0,0 +1,119 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
using ShipyardFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardFileImplement.Implements
{
public class ShopStorage:IShopStorage
{
private readonly DataFileSingleton source;
public ShopStorage()
{
source = DataFileSingleton.GetInstance();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
return source.Shops
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
return source.Shops
.Where(x => x.ShopName.Contains(model.ShopName))
.Select(x => x.GetViewModel)
.ToList();
}
public List<ShopViewModel> GetFullList()
{
return source.Shops.Select(x => x.GetViewModel).ToList();
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
source.Shops.Add(newShop);
source.SaveShops();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
source.SaveShops();
return shop.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
source.SaveShops();
return shop.GetViewModel;
}
public bool ShipsAreAvailable(IShipModel model, int requiredQuantity)
{
int availableQuantity = source.Shops.Select(x => x.Ships.FirstOrDefault(y => y.Key == model.Id).Value.Item2).Sum();
return availableQuantity >= requiredQuantity;
}
public bool SellShips(IShipModel model, int count)
{
if (!ShipsAreAvailable(model, count))
{
return false;
}
var shops = source.Shops.Where(x => x.Ships.ContainsKey(model.Id));
foreach (var shop in shops)
{
int countInCurrentShop = shop.Ships[model.Id].Item2;
if (countInCurrentShop <= count)
{
shop.Ships[model.Id] = (shop.Ships[model.Id].Item1, 0);
count -= countInCurrentShop;
}
else
{
shop.Ships[model.Id] = (shop.Ships[model.Id].Item1, countInCurrentShop - count);
count = 0;
}
if (count == 0)
{
return true;
}
}
return false;
}
}
}

View File

@ -0,0 +1,109 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ShipyardFileImplement.Models
{
public class Shop:IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpen { get; private set; }
public int Capacity { get; private set; }
public Dictionary<int, int> ShipsCount = new();
public Dictionary<int, (IShipModel, int)>? _ships = null;
public Dictionary<int, (IShipModel, int)> Ships
{
get
{
if (_ships == null)
{
var source = DataFileSingleton.GetInstance();
_ships = ShipsCount.ToDictionary(
x => x.Key,
y => ((source.Ships.FirstOrDefault(z => z.Id == y.Key) as IShipModel)!,
y.Value)
);
}
return _ships;
}
}
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpen = model.DateOpen,
Capacity = model.Capacity,
ShipsCount = model.Ships.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Shop()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
DateOpen = Convert.ToDateTime(element.Element("DateOpening")!.Value),
Capacity = Convert.ToInt32(element.Element("Capacity")!.Value),
ShipsCount = element.Element("Ships")!.Elements("Ship")
.ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpen = model.DateOpen;
Capacity = model.Capacity;
ShipsCount = model.Ships.ToDictionary(x => x.Key, x => x.Value.Item2);
_ships = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpen = DateOpen,
Capacity = Capacity,
Ships = Ships
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpening", DateOpen.ToString()),
new XElement("Capacity", Capacity.ToString()),
new XElement("Ships", ShipsCount.Select(x =>
new XElement("Ship",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}

View File

@ -2,6 +2,7 @@
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
using ShipyardListImplement;
using ShipyardListImplement.Models;
using System;
@ -109,5 +110,14 @@ namespace ShipyardListImplement.Implements
}
return null;
}
public bool ShipsAreAvailable(IShipModel model, int requiredQuantity)
{
throw new NotImplementedException();
}
public bool SellShips(IShipModel model, int count)
{
throw new NotImplementedException();
}
}
}

View File

@ -16,6 +16,7 @@ namespace ShipyardListImplement.Models
public string Address { get; set; } = string.Empty;
public DateTime DateOpen { get; set; }
public int Capacity { get; private set; }
public int Id { get; set; }
public Dictionary<int, (IShipModel, int)> Ships { get; private set; } = new Dictionary<int, (IShipModel, int)>();