LabWork02_Hard: Вроде готово, возможны фиксы после тестов

This commit is contained in:
Safgerd 2023-03-26 02:47:18 +04:00
parent 7afe26c398
commit f0da36541e
21 changed files with 814 additions and 22 deletions

View File

@ -40,6 +40,7 @@
this.buttonSetToDone = new System.Windows.Forms.Button();
this.buttonSetToFinish = new System.Windows.Forms.Button();
this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonSellCars = new System.Windows.Forms.Button();
this.menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
@ -156,11 +157,22 @@
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.ButtonUpdate_Click);
//
// buttonSellCars
//
this.buttonSellCars.Location = new System.Drawing.Point(969, 218);
this.buttonSellCars.Name = "buttonSellCars";
this.buttonSellCars.Size = new System.Drawing.Size(194, 29);
this.buttonSellCars.TabIndex = 7;
this.buttonSellCars.Text = "Продажа автомобилей";
this.buttonSellCars.UseVisualStyleBackColor = true;
this.buttonSellCars.Click += new System.EventHandler(this.buttonSellCars_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1176, 450);
this.Controls.Add(this.buttonSellCars);
this.Controls.Add(this.buttonSupplyShop);
this.Controls.Add(this.buttonUpdate);
this.Controls.Add(this.buttonSetToFinish);
@ -195,5 +207,6 @@
private Button buttonUpdate;
private ToolStripMenuItem магазиныToolStripMenuItem;
private Button buttonSupplyShop;
private Button buttonSellCars;
}
}

View File

@ -182,5 +182,14 @@ namespace AutomobilePlant
form.ShowDialog();
}
}
private void buttonSellCars_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShopSell));
if (service is FormShopSell form)
{
form.ShowDialog();
}
}
}
}

View File

@ -36,10 +36,12 @@
this.ColumnId = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCarName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.openingDateLabel = new System.Windows.Forms.Label();
this.openingDateTimePicker = new System.Windows.Forms.DateTimePicker();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.labelMaxCount = new System.Windows.Forms.Label();
this.textBoxMaxCountCars = new System.Windows.Forms.TextBox();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
@ -82,11 +84,11 @@
this.ColumnId,
this.ColumnCarName,
this.ColumnCount});
this.dataGridView.Location = new System.Drawing.Point(14, 127);
this.dataGridView.Location = new System.Drawing.Point(14, 173);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(401, 289);
this.dataGridView.Size = new System.Drawing.Size(401, 265);
this.dataGridView.TabIndex = 10;
//
// ColumnId
@ -147,11 +149,28 @@
this.openingDateTimePicker.Size = new System.Drawing.Size(274, 27);
this.openingDateTimePicker.TabIndex = 14;
//
// labelMaxCount
//
this.labelMaxCount.AutoSize = true;
this.labelMaxCount.Location = new System.Drawing.Point(18, 128);
this.labelMaxCount.Name = "labelMaxCount";
this.labelMaxCount.Size = new System.Drawing.Size(216, 20);
this.labelMaxCount.TabIndex = 13;
this.labelMaxCount.Text = "Макс. количество авто";
//
// textBoxMaxCountCars
//
this.textBoxMaxCountCars.Location = new System.Drawing.Point(240, 128);
this.textBoxMaxCountCars.Name = "textBoxMaxCountCars";
this.textBoxMaxCountCars.Size = new System.Drawing.Size(175, 27);
this.textBoxMaxCountCars.TabIndex = 14;
// FormShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(445, 489);
this.Controls.Add(this.textBoxMaxCountCars);
this.Controls.Add(this.labelMaxCount);
this.Controls.Add(this.openingDateTimePicker);
this.Controls.Add(this.openingDateLabel);
this.Controls.Add(this.buttonCancel);
@ -184,5 +203,7 @@
private DataGridViewTextBoxColumn ColumnCount;
private Label openingDateLabel;
private DateTimePicker openingDateTimePicker;
private Label labelMaxCount;
private TextBox textBoxMaxCountCars;
}
}

View File

@ -47,6 +47,7 @@ namespace AutomobilePlant
textBoxAddress.Text = view.Address;
openingDateTimePicker.Value = view.OpeningDate;
_shopCars = view.ShopCars ?? new Dictionary<int, (ICarModel, int)>();
textBoxMaxCountCars.Text = view.MaxCountCars.ToString();
LoadData();
}
}
@ -94,6 +95,12 @@ namespace AutomobilePlant
return;
}
if (string.IsNullOrEmpty(textBoxMaxCountCars.Text))
{
MessageBox.Show("Заполните макс. количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение магазина");
try
@ -104,7 +111,8 @@ namespace AutomobilePlant
Name = textBoxName.Text,
Address = textBoxAddress.Text,
OpeningDate = openingDateTimePicker.Value.Date,
ShopCars= _shopCars
MaxCountCars = Convert.ToInt32(textBoxMaxCountCars.Text),
ShopCars = _shopCars
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);

View File

@ -0,0 +1,119 @@
namespace AutomobilePlant
{
partial class FormShopSell
{
/// <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.labelCount = new System.Windows.Forms.Label();
this.labelCar = new System.Windows.Forms.Label();
this.comboBoxCar = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonSell = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(23, 76);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(93, 20);
this.labelCount.TabIndex = 1;
this.labelCount.Text = "Количество:";
//
// labelCar
//
this.labelCar.AutoSize = true;
this.labelCar.Location = new System.Drawing.Point(23, 24);
this.labelCar.Name = "labelCar";
this.labelCar.Size = new System.Drawing.Size(79, 20);
this.labelCar.TabIndex = 2;
this.labelCar.Text = "Автомобиль:";
//
// comboBoxCar
//
this.comboBoxCar.FormattingEnabled = true;
this.comboBoxCar.Location = new System.Drawing.Point(124, 24);
this.comboBoxCar.Name = "comboBoxCar";
this.comboBoxCar.Size = new System.Drawing.Size(278, 28);
this.comboBoxCar.TabIndex = 4;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(124, 73);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(158, 27);
this.textBoxCount.TabIndex = 5;
//
// buttonSell
//
this.buttonSell.Location = new System.Drawing.Point(188, 142);
this.buttonSell.Name = "buttonSell";
this.buttonSell.Size = new System.Drawing.Size(94, 29);
this.buttonSell.TabIndex = 6;
this.buttonSell.Text = "Продажа";
this.buttonSell.UseVisualStyleBackColor = true;
this.buttonSell.Click += new System.EventHandler(this.buttonSell_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(308, 142);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 7;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormShopSell
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(459, 198);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSell);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxCar);
this.Controls.Add(this.labelCar);
this.Controls.Add(this.labelCount);
this.Name = "FormShopSell";
this.Text = "Продажа из магазина";
this.Load += new System.EventHandler(this.FormShopSell_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelCount;
private Label labelCar;
private ComboBox comboBoxCar;
private TextBox textBoxCount;
private Button buttonSell;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,95 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutomobilePlant
{
public partial class FormShopSell : Form
{
private readonly ILogger _logger;
private readonly ICarLogic _logicCar;
private readonly IShopLogic _logicShop;
public FormShopSell(ILogger<FormShopSell> logger, ICarLogic logicCar, IShopLogic logicShop)
{
InitializeComponent();
_logger = logger;
_logicCar = logicCar;
_logicShop = logicShop;
}
private void FormShopSell_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка авто для продажи");
try
{
var list = _logicCar.ReadList(null);
if (list != null)
{
comboBoxCar.DisplayMember = "CarName";
comboBoxCar.ValueMember = "Id";
comboBoxCar.DataSource = list;
comboBoxCar.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка авто");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSell_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxCar.SelectedValue == null)
{
MessageBox.Show("Выберите авто", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание продажи");
try
{
var operationResult = _logicShop.SellCar(
new CarBindingModel
{
Id = Convert.ToInt32(comboBoxCar.SelectedValue)
},
Convert.ToInt32(textBoxCount.Text)
);
if (!operationResult)
{
throw new Exception("Ошибка при создании продажи. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания продажи");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

View File

@ -48,6 +48,7 @@ namespace AutomobilePlant
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormShopSupply>();
services.AddTransient<FormShopSell>();
}
}
}

View File

@ -4,6 +4,7 @@ using AutomobilePlantContracts.SearchModels;
using AutomobilePlantContracts.StorageContracts;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Enums;
using AutomobilePlantDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@ -17,11 +18,17 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly IShopLogic _shopLogic;
private readonly ICarStorage _carStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopLogic shopLogic, ICarStorage carStorage, IShopStorage shopStorage)
{
_logger = logger;
_orderStorage = orderStorage;
_shopLogic = shopLogic;
_carStorage = carStorage;
_shopStorage = shopStorage;
}
public bool CreateOrder(OrderBindingModel model)
@ -72,6 +79,20 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Order status incorrect.");
return false;
}
if (newStatus == OrderStatus.Готов)
{
var car = _carStorage.GetElement(new CarSearchModel() { Id = model.CarId });
if (car == null)
{
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Document not found.");
return false;
}
if (CheckThenSupplyMany(car, model.Count) == false)
{
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Shop supply error.");
return false;
}
}
model.Status = newStatus;
if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now;
if (_orderStorage.Update(model) == null)
@ -83,6 +104,67 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
return true;
}
public bool CheckThenSupplyMany(ICarModel car, int count)
{
if (count <= 0)
{
_logger.LogWarning("Check then supply operation error. Car count < 0.");
return false;
}
int freeSpace = 0;
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace += shop.MaxCountCars;
foreach (var c in shop.ShopCars)
{
freeSpace -= c.Value.Item2;
}
}
if (freeSpace - count < 0)
{
_logger.LogWarning("Check then supply operation error. There's no place for new cars in shops.");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace = shop.MaxCountCars;
foreach (var c in shop.ShopCars)
{
freeSpace -= c.Value.Item2;
}
if (freeSpace == 0)
{
continue;
}
if (freeSpace - count >= 0)
{
if (_shopLogic.SupplyCars(new() { Id = shop.Id }, car, count)) count = 0;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (freeSpace - count < 0)
{
if (_shopLogic.SupplyCars(new() { Id = shop.Id }, car, freeSpace)) count -= freeSpace;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выполняется);

View File

@ -8,6 +8,7 @@ using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
@ -88,6 +89,13 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
_logger.LogInformation("Shop element found. ID: {0}, Name: {1}", shopElement.Id, shopElement.Name);
var countCars = 0;
foreach (var c in shopElement.ShopCars)
{
countCars += c.Value.Item2;
}
if (shopElement.MaxCountCars - countCars >= count)
{
if (shopElement.ShopCars.TryGetValue(car.Id, out var sameCar))
{
shopElement.ShopCars[car.Id] = (car, sameCar.Item2 + count);
@ -98,15 +106,21 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
shopElement.ShopCars[car.Id] = (car, count);
_logger.LogInformation("New car added by supply. Added {0} of {1} in {2} shop", count, car.CarName, shopElement.Name);
}
_shopStorage.Update(new()
{
Id = shopElement.Id,
Name = shopElement.Name,
Address = shopElement.Address,
OpeningDate = shopElement.OpeningDate,
ShopCars = shopElement.ShopCars
ShopCars = shopElement.ShopCars,
MaxCountCars = shopElement.MaxCountCars
});
}
else
{
_logger.LogWarning("Required shop is overflowed");
return false;
}
return true;
}
@ -124,6 +138,11 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
return true;
}
public bool SellCar(ICarModel car, int count)
{
return _shopStorage.SellCar(car, count);
}
public bool Update(ShopBindingModel model)
{
CheckModel(model);
@ -167,6 +186,11 @@ namespace AutomobilePlantBusinessLogic.BusinessLogics
throw new ArgumentNullException("Нет названия магазина!", nameof(model.Name));
}
if (model.MaxCountCars < 0)
{
throw new InvalidOperationException("Магазин с отрицательным количеством максимального количества документов!");
}
_logger.LogInformation("Shop. Name: {0}, Address: {1}, ID: {2}", model.Name, model.Address, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel

View File

@ -18,5 +18,6 @@ namespace AutomobilePlantContracts.BindingModels
public DateTime OpeningDate { get; set; }
public Dictionary<int, (ICarModel, int)> ShopCars { get; set; }
public int MaxCountCars { get; set; }
}
}

View File

@ -18,5 +18,6 @@ namespace AutomobilePlantContracts.BusinessLogicContracts
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool SupplyCars(ShopSearchModel model, ICarModel car, int count);
bool SellCar(ICarModel document, int count);
}
}

View File

@ -1,6 +1,7 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModels;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
@ -17,5 +18,6 @@ namespace AutomobilePlantContracts.StorageContracts
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool SellCar(ICarModel model, int count);
}
}

View File

@ -22,5 +22,8 @@ namespace AutomobilePlantContracts.ViewModels
public DateTime OpeningDate { get; set; }
public Dictionary<int, (ICarModel, int)> ShopCars { get; set; } = new();
[DisplayName("Макс. автомобилей в магазине")]
public int MaxCountCars { get; set; }
}
}

View File

@ -12,5 +12,6 @@ namespace AutomobilePlantDataModels.Models
string Address { get; }
DateTime OpeningDate { get; }
Dictionary<int, (ICarModel, int)> ShopCars { get; }
int MaxCountCars { get; }
}
}

View File

@ -16,9 +16,12 @@ namespace AutomobilePlantFileImplement
private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string CarFileName = "Car.xml";
private readonly string ShopFileName = "Shop.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Car> Cars { get; private set; }
public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -30,11 +33,13 @@ namespace AutomobilePlantFileImplement
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
public void SaveCars() => SaveData(Cars, CarFileName, "Cars", 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()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Cars = LoadData(CarFileName, "Car", x => Car.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,155 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModels;
using AutomobilePlantContracts.StorageContracts;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models;
using AutomobilePlantFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton source;
public ShopStorage()
{
source = DataFileSingleton.GetInstance();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return source.Shops.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
return source.Shops
.Select(x => x.GetViewModel)
.Where(x => x.Name.Contains(model.Name ?? string.Empty))
.ToList();
}
public List<ShopViewModel> GetFullList()
{
return source.Shops.Select(shop => shop.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;
}
source.Shops.Remove(shop);
source.SaveShops();
return shop.GetViewModel;
}
public bool SellCar(ICarModel model, int count)
{
// переделать под linq
var car = source.Cars.FirstOrDefault(x => x.Id == model.Id);
var countStore = count;
if (car == null)
{
return false;
}
foreach (var shop in source.Shops)
{
foreach (var c in shop.ShopCars)
{
if (c.Value.Item1.Id == car.Id)
{
count -= c.Value.Item2;
}
if (count <= 0)
{
break;
}
}
}
if (count > 0)
{
return false;
}
count = countStore;
for (int i = 0; i < source.Shops.Count; i++)
{
var shop = source.Shops[i];
var cars = shop.ShopCars;
foreach (var c in cars.Where(x => x.Value.Item1.Id == car.Id))
{
var min = Math.Min(c.Value.Item2, count);
cars[c.Value.Item1.Id] = (c.Value.Item1, c.Value.Item2 - min);
count -= min;
if (count <= 0)
{
break;
}
}
shop.Update(new ShopBindingModel
{
Id = shop.Id,
Name = shop.Name,
Address = shop.Address,
OpeningDate = shop.OpeningDate,
MaxCountCars = shop.MaxCountCars,
ShopCars = cars
});
source.SaveShops();
}
if (count > 0)
{
return false;
}
return true;
}
}
}

View File

@ -14,7 +14,6 @@ namespace AutomobilePlantFileImplement.Models
public class Component : IComponentModel
{
public string ComponentName { get; private set; } = String.Empty;
public double Cost { get; set; }
public int Id { get; private set; }

View File

@ -0,0 +1,122 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AutomobilePlantFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string Name { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public int MaxCountCars { get; private set; }
public DateTime OpeningDate { get; private set; }
public Dictionary<int, int> Cars { get; private set; } = new();
private Dictionary<int, (ICarModel, int)>? _shopCars = null;
public Dictionary<int, (ICarModel, int)> ShopCars
{
get
{
if (_shopCars == null)
{
var source = DataFileSingleton.GetInstance();
_shopCars = Cars.ToDictionary(
x => x.Key,
y => ((source.Cars.FirstOrDefault(z => z.Id == y.Key) as ICarModel)!, y.Value)
);
}
return _shopCars;
}
}
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
Name = model.Name,
Address = model.Address,
MaxCountCars = model.MaxCountCars,
OpeningDate = model.OpeningDate,
Cars = model.ShopCars.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),
Name = element.Element("Name")!.Value,
Address = element.Element("Address")!.Value,
MaxCountCars = Convert.ToInt32(element.Element("MaxCountCars")!.Value),
OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value),
Cars = element.Element("ShopCars")!.Elements("ShopCar").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)
)
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
Address = model.Address;
OpeningDate = model.OpeningDate;
MaxCountCars = model.MaxCountCars;
if (model.ShopCars.Count > 0)
{
Cars = model.ShopCars.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopCars = null;
}
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Address = Address,
OpeningDate = OpeningDate,
ShopCars = ShopCars,
MaxCountCars = MaxCountCars
};
public XElement GetXElement => new(
"Shop",
new XAttribute("Id", Id),
new XElement("Name", Name),
new XElement("Address", Address),
new XElement("MaxCountCars", MaxCountCars),
new XElement("OpeningDate", OpeningDate.ToString()),
new XElement("ShopCars", Cars.Select(x =>
new XElement("ShopCar",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}

View File

@ -3,6 +3,7 @@ using AutomobilePlantContracts.SearchModels;
using AutomobilePlantContracts.StorageContracts;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantListImplements.Models;
using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
@ -122,5 +123,10 @@ namespace AutomobilePlantListImplements.Implements
return null;
}
public bool SellCar(ICarModel model, int count)
{
throw new NotImplementedException();
}
}
}

View File

@ -19,6 +19,8 @@ namespace AutomobilePlantListImplements.Models
public DateTime OpeningDate { get; private set; }
public int MaxCountCars { get; private set; }
public Dictionary<int, (ICarModel, int)> ShopCars { get; private set; } = new();
public static Shop? Create(ShopBindingModel model)
@ -34,6 +36,7 @@ namespace AutomobilePlantListImplements.Models
Name = model.Name,
Address = model.Address,
OpeningDate = model.OpeningDate,
MaxCountCars = model.MaxCountCars,
ShopCars = new()
};
}
@ -49,6 +52,7 @@ namespace AutomobilePlantListImplements.Models
Address = model.Address;
OpeningDate = model.OpeningDate;
ShopCars = model.ShopCars;
MaxCountCars= model.MaxCountCars;
}
public ShopViewModel GetViewModel => new()
@ -57,7 +61,8 @@ namespace AutomobilePlantListImplements.Models
Name = Name,
Address = Address,
OpeningDate = OpeningDate,
ShopCars = ShopCars
ShopCars = ShopCars,
MaxCountCars = MaxCountCars
};
}
}