Borschevskaya A.A. Lab work 6 #10

Closed
pgirl1 wants to merge 11 commits from lab6_base into lab5_base
43 changed files with 2164 additions and 87 deletions

View File

@ -15,10 +15,12 @@ namespace FurnitureAssemFileImplement
private readonly string OrderFileName = "Order.xml";
private readonly string FurnitureFileName = "Furniture.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Furniture> Furnitures { get; private set; }
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -31,12 +33,14 @@ namespace FurnitureAssemFileImplement
public void SaveFurnitures() => SaveData(Furnitures, FurnitureFileName, "Furnitures", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Furnitures = LoadData(FurnitureFileName, "Furniture", x => Furniture.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)

View File

@ -0,0 +1,99 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemFileImplement.Models;
namespace FurnitureAssemFileImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataFileSingleton source;
public ImplementerStorage()
{
source = DataFileSingleton.GetInstance();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue && string.IsNullOrEmpty(model.Password))
{
return null;
}
if (model.Id.HasValue)
{
return source.Implementers
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
}
if (model.ImplementerFIO != null && model.Password != null)
{
return source.Implementers
.FirstOrDefault(x =>
x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))
?.GetViewModel;
}
return source.Implementers
.FirstOrDefault(x =>
x.ImplementerFIO.Equals(model.ImplementerFIO))
?.GetViewModel;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return new();
}
return source.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
public List<ImplementerViewModel> GetFullList()
{
return source.Implementers
.Select(x => x.GetViewModel)
.ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = source.Implementers.Count > 0 ? source.Implementers.Max(x => x.Id) + 1 : 1;
var newImpl = Implementer.Create(model);
if (newImpl == null)
{
return null;
}
source.Implementers.Add(newImpl);
source.SaveComponents();
return newImpl.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (implementer == null)
{
return null;
}
implementer.Update(model);
source.SaveComponents();
return implementer.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var element = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Implementers.Remove(element);
source.SaveComponents();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -27,7 +27,7 @@ namespace FurnitureAssemFileImplement.Implements
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue)
if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue && !model.Status.HasValue)
{
return new();
}
@ -39,21 +39,23 @@ namespace FurnitureAssemFileImplement.Implements
.ToList();
}
return source.Orders
.Where(x => !(((model.DateFrom.HasValue) && (model.DateTo.HasValue)) && !(model.DateFrom <= x.DateCreate && x.DateCreate <= model.DateTo) ||
(model.ClientId.HasValue) && !(x.ClientId.Equals(model.ClientId))))
.Where(x => !(((model.DateFrom.HasValue) && (model.DateTo.HasValue)) && !(model.DateFrom <= x.DateCreate && x.DateCreate <= model.DateTo)
|| ((model.ClientId.HasValue) && !(x.ClientId.Equals(model.ClientId)))
|| ((model.Status.HasValue) && !(x.Status.Equals(model.Status)))
))
.Select(x => GetOrderViewModel(x))
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
if (!model.Id.HasValue && (!model.ImplementerId.HasValue || !model.Status.HasValue))
{
return null;
}
var order = source.Orders
.FirstOrDefault(x =>
(model.Id.HasValue && x.Id == model.Id));
(model.Id.HasValue && x.Id == model.Id) || (x.ImplementerId.Equals(model.ImplementerId) && x.Status.Equals(model.Status)));
return GetOrderViewModel(order);
}

View File

@ -0,0 +1,79 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Models;
using System.Xml.Linq;
namespace FurnitureAssemFileImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
public static Implementer? Create(ImplementerBindingModel? model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
ImplementerFIO = model.ImplementerFIO,
Password = model.Password,
WorkExperience = model.WorkExperience,
Qualification = model.Qualification
};
}
public static Implementer? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Implementer()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ImplementerFIO = element.Element("ImplementerFIO")!.Value,
Password = element.Element("Password")!.Value,
WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value),
Qualification = Convert.ToInt32(element.Element("Qualification")!.Value)
};
}
public void Update(ImplementerBindingModel? model)
{
if (model == null)
{
return;
}
ImplementerFIO = model.ImplementerFIO;
Password = model.Password;
WorkExperience = model.WorkExperience;
Qualification = model.Qualification;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
ImplementerFIO = ImplementerFIO,
Password = Password,
WorkExperience = WorkExperience,
Qualification = Qualification
};
public XElement GetXElement => new("Implementer",
new XAttribute("Id", Id),
new XElement("ImplementerFIO", ImplementerFIO),
new XElement("Password", Password),
new XElement("WorkExperience", WorkExperience.ToString()),
new XElement("Qualification", Qualification.ToString())
);
}
}

View File

@ -33,6 +33,8 @@ namespace FurnitureAssemFileImplement.Models
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; } = null;
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
@ -48,7 +50,8 @@ namespace FurnitureAssemFileImplement.Models
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ClientId = model.ClientId
ClientId = model.ClientId,
ImplementerId = model.ImplementerId
};
}
@ -65,7 +68,8 @@ namespace FurnitureAssemFileImplement.Models
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null),
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value)
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
ImplementerId = Convert.ToInt32(element.Element("ImplementerId")?.Value)
};
DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl);
@ -88,6 +92,7 @@ namespace FurnitureAssemFileImplement.Models
Status = model.Status;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
}
public OrderViewModel GetViewModel => new()
@ -99,7 +104,8 @@ namespace FurnitureAssemFileImplement.Models
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
ClientId = ClientId
ClientId = ClientId,
ImplementerId = ImplementerId
};
public XElement GetXElement => new("Order",
@ -110,6 +116,7 @@ namespace FurnitureAssemFileImplement.Models
new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()),
new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString()));
new XElement("DateImplement", DateImplement.ToString()),
new XElement("ImplemwenterId", ImplementerId.ToString()));
}
}

View File

@ -0,0 +1,167 @@
namespace FurnitureAssembly
{
partial class FormImplementer
{
/// <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.ButtonSave = new System.Windows.Forms.Button();
this.textBoxFIO = new System.Windows.Forms.TextBox();
this.textBoxPassword = new System.Windows.Forms.TextBox();
this.labelName = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.numericUpDownWE = new System.Windows.Forms.NumericUpDown();
this.numericUpDownQual = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWE)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownQual)).BeginInit();
this.SuspendLayout();
//
// ButtonCancel
//
this.ButtonCancel.Location = new System.Drawing.Point(335, 221);
this.ButtonCancel.Name = "ButtonCancel";
this.ButtonCancel.Size = new System.Drawing.Size(75, 23);
this.ButtonCancel.TabIndex = 7;
this.ButtonCancel.Text = "Отмена";
this.ButtonCancel.UseVisualStyleBackColor = true;
this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// ButtonSave
//
this.ButtonSave.Location = new System.Drawing.Point(231, 221);
this.ButtonSave.Name = "ButtonSave";
this.ButtonSave.Size = new System.Drawing.Size(75, 23);
this.ButtonSave.TabIndex = 6;
this.ButtonSave.Text = "Сохранить";
this.ButtonSave.UseVisualStyleBackColor = true;
this.ButtonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// textBoxFIO
//
this.textBoxFIO.Location = new System.Drawing.Point(129, 33);
this.textBoxFIO.Name = "textBoxFIO";
this.textBoxFIO.Size = new System.Drawing.Size(281, 23);
this.textBoxFIO.TabIndex = 8;
//
// textBoxPassword
//
this.textBoxPassword.Location = new System.Drawing.Point(129, 74);
this.textBoxPassword.Name = "textBoxPassword";
this.textBoxPassword.Size = new System.Drawing.Size(281, 23);
this.textBoxPassword.TabIndex = 9;
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(31, 36);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(34, 15);
this.labelName.TabIndex = 12;
this.labelName.Text = "ФИО";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(31, 77);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(49, 15);
this.label1.TabIndex = 13;
this.label1.Text = "Пароль";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(31, 117);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(79, 15);
this.label2.TabIndex = 14;
this.label2.Text = "Стаж работы";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(31, 160);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(88, 15);
this.label3.TabIndex = 15;
this.label3.Text = "Квалификация";
//
// numericUpDownWE
//
this.numericUpDownWE.Location = new System.Drawing.Point(129, 115);
this.numericUpDownWE.Name = "numericUpDownWE";
this.numericUpDownWE.Size = new System.Drawing.Size(120, 23);
this.numericUpDownWE.TabIndex = 16;
//
// numericUpDownQual
//
this.numericUpDownQual.Location = new System.Drawing.Point(129, 158);
this.numericUpDownQual.Name = "numericUpDownQual";
this.numericUpDownQual.Size = new System.Drawing.Size(120, 23);
this.numericUpDownQual.TabIndex = 17;
//
// FormImplementer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(423, 263);
this.Controls.Add(this.numericUpDownQual);
this.Controls.Add(this.numericUpDownWE);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.labelName);
this.Controls.Add(this.textBoxPassword);
this.Controls.Add(this.textBoxFIO);
this.Controls.Add(this.ButtonCancel);
this.Controls.Add(this.ButtonSave);
this.Name = "FormImplementer";
this.Text = "Исполнитель";
this.Load += new System.EventHandler(this.FormImplementer_Load);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWE)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownQual)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button ButtonCancel;
private Button ButtonSave;
private TextBox textBoxFIO;
private TextBox textBoxPassword;
private Label labelName;
private Label label1;
private Label label2;
private Label label3;
private NumericUpDown numericUpDownWE;
private NumericUpDown numericUpDownQual;
}
}

View File

@ -0,0 +1,109 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using FurnitureAssemblyContracts.SearchModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FurnitureAssembly
{
public partial class FormImplementer : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormImplementer(ILogger<FormImplementer> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormImplementer_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение исполнителя");
var view = _logic.ReadElement(new ImplementerSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxFIO.Text = view.ImplementerFIO;
textBoxPassword.Text = view.Password;
numericUpDownWE.Value = view.WorkExperience;
numericUpDownQual.Value = view.Qualification;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxFIO.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPassword.Text))
{
MessageBox.Show("Заполните пароль", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = textBoxFIO.Text,
Password = textBoxPassword.Text,
WorkExperience = Convert.ToInt32(numericUpDownWE.Value),
Qualification = Convert.ToInt32(numericUpDownQual.Value),
};
var operationResult = _id.HasValue ? _logic.Update(model) :
_logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}

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

@ -0,0 +1,114 @@
namespace FurnitureAssembly
{
partial class FormImplementers
{
/// <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.dataGridView = new System.Windows.Forms.DataGridView();
this.ButtonRef = new System.Windows.Forms.Button();
this.ButtonDel = new System.Windows.Forms.Button();
this.ButtonUpd = new System.Windows.Forms.Button();
this.ButtonAdd = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(2, 0);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(559, 450);
this.dataGridView.TabIndex = 7;
//
// ButtonRef
//
this.ButtonRef.Location = new System.Drawing.Point(590, 244);
this.ButtonRef.Name = "ButtonRef";
this.ButtonRef.Size = new System.Drawing.Size(105, 29);
this.ButtonRef.TabIndex = 11;
this.ButtonRef.Text = "Обновить";
this.ButtonRef.UseVisualStyleBackColor = true;
this.ButtonRef.Click += new System.EventHandler(this.ButtonRef_Click);
//
// ButtonDel
//
this.ButtonDel.Location = new System.Drawing.Point(590, 186);
this.ButtonDel.Name = "ButtonDel";
this.ButtonDel.Size = new System.Drawing.Size(105, 29);
this.ButtonDel.TabIndex = 10;
this.ButtonDel.Text = "Удалить";
this.ButtonDel.UseVisualStyleBackColor = true;
this.ButtonDel.Click += new System.EventHandler(this.ButtonDel_Click);
//
// ButtonUpd
//
this.ButtonUpd.Location = new System.Drawing.Point(590, 129);
this.ButtonUpd.Name = "ButtonUpd";
this.ButtonUpd.Size = new System.Drawing.Size(105, 29);
this.ButtonUpd.TabIndex = 9;
this.ButtonUpd.Text = "Изменить";
this.ButtonUpd.UseVisualStyleBackColor = true;
this.ButtonUpd.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// ButtonAdd
//
this.ButtonAdd.Location = new System.Drawing.Point(590, 73);
this.ButtonAdd.Name = "ButtonAdd";
this.ButtonAdd.Size = new System.Drawing.Size(105, 29);
this.ButtonAdd.TabIndex = 8;
this.ButtonAdd.Text = "Добавить";
this.ButtonAdd.UseVisualStyleBackColor = true;
this.ButtonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// FormImplementers
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(718, 450);
this.Controls.Add(this.ButtonRef);
this.Controls.Add(this.ButtonDel);
this.Controls.Add(this.ButtonUpd);
this.Controls.Add(this.ButtonAdd);
this.Controls.Add(this.dataGridView);
this.Name = "FormImplementers";
this.Text = "Исполнители";
this.Load += new System.EventHandler(this.FormImplementers_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button ButtonRef;
private Button ButtonDel;
private Button ButtonUpd;
private Button ButtonAdd;
}
}

View File

@ -0,0 +1,112 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using Microsoft.Extensions.Logging;
namespace FurnitureAssembly
{
public partial class FormImplementers : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
public FormImplementers(ILogger<FormImplementers> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormImplementers_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки исполнителей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer form)
{
form.Id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление исполнителя");
try
{
if (!_logic.Delete(new ImplementerBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления исполнителя");
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

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

@ -30,8 +30,6 @@
{
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ButtonCreateOrder = new System.Windows.Forms.Button();
this.ButtonTakeOrderInWork = new System.Windows.Forms.Button();
this.ButtonOrderReady = new System.Windows.Forms.Button();
this.ButtonIssuedOrder = new System.Windows.Forms.Button();
this.ButtonRef = new System.Windows.Forms.Button();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
@ -39,10 +37,12 @@
this.компонентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.изделияToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ClientsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ImplementersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.отчетыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.FurnituresToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.FurnituresComponentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.списокЗаказовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.doWorkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
@ -66,29 +66,9 @@
this.ButtonCreateOrder.UseVisualStyleBackColor = true;
this.ButtonCreateOrder.Click += new System.EventHandler(this.ButtonCreateOrder_Click);
//
// ButtonTakeOrderInWork
//
this.ButtonTakeOrderInWork.Location = new System.Drawing.Point(902, 122);
this.ButtonTakeOrderInWork.Name = "ButtonTakeOrderInWork";
this.ButtonTakeOrderInWork.Size = new System.Drawing.Size(150, 25);
this.ButtonTakeOrderInWork.TabIndex = 2;
this.ButtonTakeOrderInWork.Text = "Отдать на выполнение";
this.ButtonTakeOrderInWork.UseVisualStyleBackColor = true;
this.ButtonTakeOrderInWork.Click += new System.EventHandler(this.ButtonTakeOrderInWork_Click);
//
// ButtonOrderReady
//
this.ButtonOrderReady.Location = new System.Drawing.Point(902, 173);
this.ButtonOrderReady.Name = "ButtonOrderReady";
this.ButtonOrderReady.Size = new System.Drawing.Size(150, 25);
this.ButtonOrderReady.TabIndex = 3;
this.ButtonOrderReady.Text = "Заказ готов";
this.ButtonOrderReady.UseVisualStyleBackColor = true;
this.ButtonOrderReady.Click += new System.EventHandler(this.ButtonOrderReady_Click);
//
// ButtonIssuedOrder
//
this.ButtonIssuedOrder.Location = new System.Drawing.Point(902, 223);
this.ButtonIssuedOrder.Location = new System.Drawing.Point(903, 116);
this.ButtonIssuedOrder.Name = "ButtonIssuedOrder";
this.ButtonIssuedOrder.Size = new System.Drawing.Size(150, 25);
this.ButtonIssuedOrder.TabIndex = 4;
@ -98,7 +78,7 @@
//
// ButtonRef
//
this.ButtonRef.Location = new System.Drawing.Point(902, 273);
this.ButtonRef.Location = new System.Drawing.Point(902, 165);
this.ButtonRef.Name = "ButtonRef";
this.ButtonRef.Size = new System.Drawing.Size(150, 25);
this.ButtonRef.TabIndex = 5;
@ -110,7 +90,8 @@
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.справочникиToolStripMenuItem,
this.отчетыToolStripMenuItem});
this.отчетыToolStripMenuItem,
this.doWorkToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(1065, 24);
@ -122,7 +103,8 @@
this.справочникиToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.компонентыToolStripMenuItem,
this.изделияToolStripMenuItem,
this.ClientsMenuItem});
this.ClientsMenuItem,
this.ImplementersToolStripMenuItem});
this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(94, 20);
this.справочникиToolStripMenuItem.Text = "Справочники";
@ -130,24 +112,31 @@
// компонентыToolStripMenuItem
//
this.компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
this.компонентыToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.компонентыToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.компонентыToolStripMenuItem.Text = "Компоненты";
this.компонентыToolStripMenuItem.Click += new System.EventHandler(this.КомпонентыToolStripMenuItem_Click);
//
// изделияToolStripMenuItem
//
this.изделияToolStripMenuItem.Name = "изделияToolStripMenuItem";
this.изделияToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.изделияToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.изделияToolStripMenuItem.Text = "Изделия";
this.изделияToolStripMenuItem.Click += new System.EventHandler(this.ИзделияToolStripMenuItem_Click);
//
// ClientsMenuItem
//
this.ClientsMenuItem.Name = "ClientsMenuItem";
this.ClientsMenuItem.Size = new System.Drawing.Size(180, 22);
this.ClientsMenuItem.Size = new System.Drawing.Size(149, 22);
this.ClientsMenuItem.Text = "Клиенты";
this.ClientsMenuItem.Click += new System.EventHandler(this.ClientsMenuItem_Click);
//
// ImplementersToolStripMenuItem
//
this.ImplementersToolStripMenuItem.Name = "ImplementersToolStripMenuItem";
this.ImplementersToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.ImplementersToolStripMenuItem.Text = "Исполнители";
this.ImplementersToolStripMenuItem.Click += new System.EventHandler(this.ImplementersToolStripMenuItem_Click);
//
// отчетыToolStripMenuItem
//
this.отчетыToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
@ -179,6 +168,13 @@
this.списокЗаказовToolStripMenuItem.Text = "Список заказов";
this.списокЗаказовToolStripMenuItem.Click += new System.EventHandler(this.OrdersToolStripMenuItem_Click);
//
// doWorkToolStripMenuItem
//
this.doWorkToolStripMenuItem.Name = "doWorkToolStripMenuItem";
this.doWorkToolStripMenuItem.Size = new System.Drawing.Size(92, 20);
this.doWorkToolStripMenuItem.Text = "Запуск работ";
this.doWorkToolStripMenuItem.Click += new System.EventHandler(this.doWorkToolStripMenuItem_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@ -186,8 +182,6 @@
this.ClientSize = new System.Drawing.Size(1065, 450);
this.Controls.Add(this.ButtonRef);
this.Controls.Add(this.ButtonIssuedOrder);
this.Controls.Add(this.ButtonOrderReady);
this.Controls.Add(this.ButtonTakeOrderInWork);
this.Controls.Add(this.ButtonCreateOrder);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.menuStrip1);
@ -207,8 +201,6 @@
private DataGridView dataGridView;
private Button ButtonCreateOrder;
private Button ButtonTakeOrderInWork;
private Button ButtonOrderReady;
private Button ButtonIssuedOrder;
private Button ButtonRef;
private MenuStrip menuStrip1;
@ -220,5 +212,7 @@
private ToolStripMenuItem FurnituresComponentsToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem ClientsMenuItem;
private ToolStripMenuItem ImplementersToolStripMenuItem;
private ToolStripMenuItem doWorkToolStripMenuItem;
}
}

View File

@ -19,12 +19,14 @@ namespace FurnitureAssembly
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
private readonly IWorkProcess _workModeling;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workModeling)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workModeling = workModeling;
}
private void FormMain_Load(object sender, EventArgs e)
{
@ -40,6 +42,7 @@ namespace FurnitureAssembly
dataGridView.DataSource = list;
dataGridView.Columns["FurnitureId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
}
_logger.LogInformation("Загрузка заказов");
}
@ -200,5 +203,21 @@ namespace FurnitureAssembly
form.ShowDialog();
}
}
private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
private void doWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
_workModeling.DoWork((
Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!,
_orderLogic);
}
}
}

View File

@ -41,12 +41,15 @@ namespace FurnitureAssembly
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IFurnitureStorage, FurnitureStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IFurnitureLogic, FurnitureLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
@ -63,6 +66,8 @@ namespace FurnitureAssembly
services.AddTransient<FormReportFurnitureComponents>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormClients>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
}
}
}

View File

@ -0,0 +1,131 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyBusinessLogic
{
public class ImplementerLogic : IImplementerLogic
{
private readonly ILogger _logger;
private readonly IImplementerStorage _implementerStorage;
public ImplementerLogic(ILogger<ImplementerLogic> logger, IImplementerStorage implementerStorage)
{
_logger = logger;
_implementerStorage = implementerStorage;
}
public bool Create(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(ImplementerBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_implementerStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public ImplementerViewModel? ReadElement(ImplementerSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ImplementerFIO: {ImplementerFIO} Id:{ Id}", model.ImplementerFIO, model.Id);
var element = _implementerStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model)
{
_logger.LogInformation("ReadList. ImplementerFIO: {ImplementerFIO}. Id:{ Id}", model?.ImplementerFIO, model?.Id);
var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Update(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
private void CheckModel(ImplementerBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
throw new ArgumentNullException("Нет ФИО исполнителя",
nameof(model.ImplementerFIO));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля пользователя",
nameof(model.Password));
}
if (model.WorkExperience < 0)
{
throw new ArgumentException("Опыт работы не должен быть отрицательным", nameof(model.WorkExperience));
}
if (model.Qualification < 0)
{
throw new ArgumentException("Квалификация не должна быть отрицательной", nameof(model.Qualification));
}
_logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Id: { Id}", model.ImplementerFIO, model.Id);
var element = _implementerStorage.GetElement(new ImplementerSearchModel { ImplementerFIO = model.ImplementerFIO });
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Исполнитель с таким логином уже есть");
}
}
}
}

View File

@ -41,7 +41,7 @@ namespace FurnitureAssemblyBusinessLogic
if (!ChangeStatus(model, OrderStatus.Принят))
{
_logger.LogWarning("Order's status is wrong");
return false;
throw new InvalidOperationException("Order's status is wrong");
}
if (_orderStorage.Insert(model) == null)
@ -55,15 +55,16 @@ namespace FurnitureAssemblyBusinessLogic
public bool TakeOrderInWork(OrderBindingModel model)
{
model = Find(model);
if (model == null)
var modelNew = ReadElement(new OrderSearchModel { Id = model.Id }); // в связи с обновлением контракта, предыдущий метод не нужен
if (modelNew == null)
{
return false;
}
model.Status = modelNew.Status;
if (!ChangeStatus(model, OrderStatus.Выполняется))
{
_logger.LogWarning("Order's status is wrong");
return false;
throw new InvalidOperationException("Order's status is wrong");
}
_orderStorage.Update(model);
return true;
@ -71,32 +72,38 @@ namespace FurnitureAssemblyBusinessLogic
public bool FinishOrder(OrderBindingModel model)
{
model = Find(model);
if (model == null) {
var modelNew = ReadElement(new OrderSearchModel { Id = model.Id}); // в связи с обновлением контракта, предыдущий метод не нужен
if (modelNew == null) {
return false;
}
model.Status = modelNew.Status;
model.ImplementerId = modelNew.ImplementerId;
if (!ChangeStatus(model, OrderStatus.Готов))
{
_logger.LogWarning("Order's status is wrong");
return false;
throw new InvalidOperationException("Order's status is wrong");
}
model.DateImplement = DateTime.Now;
_orderStorage.Update(model);
return true;
}
public bool DeliveryOrder(OrderBindingModel model)
{
model = Find(model);
if (model == null)
var modelNew = ReadElement(new OrderSearchModel { Id = model.Id }); // в связи с обновлением контракта, предыдущий метод не нужен
if (modelNew == null)
{
return false;
}
model.Status = modelNew.Status;
model.ImplementerId = modelNew.ImplementerId;
model.DateImplement = modelNew.DateImplement;
if (!ChangeStatus(model, OrderStatus.Выдан))
{
_logger.LogWarning("Order's status is wrong");
return false;
}
model.DateImplement = DateTime.Now;
_orderStorage.Update(model);
return true;
}
@ -143,20 +150,21 @@ namespace FurnitureAssemblyBusinessLogic
model.Id, model.Status, model.DateCreate, model.FurnitureId, model.Count, model.Sum);
}
private OrderBindingModel? Find(OrderBindingModel model)
public OrderViewModel? ReadElement(OrderSearchModel? model)
{
var modelView = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (modelView == null)
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Status: {Status}. ImplementerId: {ImplementerId} Id:{ Id}", model.Status, model.ImplementerId, model.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
model.FurnitureId = modelView.FurnitureId;
model.DateCreate = modelView.DateCreate;
model.Count = modelView.Count;
model.Sum = modelView.Sum;
model.FurnitureId = model.FurnitureId;
model.Status = modelView.Status;
return model;
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
}
}

View File

@ -0,0 +1,144 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Enums;
using Microsoft.Extensions.Logging;
namespace FurnitureAssemblyBusinessLogic
{
public class WorkModeling : IWorkProcess
{
private readonly ILogger _logger;
private readonly Random _rnd;
private IOrderLogic? _orderLogic;
public WorkModeling(ILogger<WorkModeling> logger)
{
_logger = logger;
_rnd = new Random(1000);
}
public void DoWork(IImplementerLogic implementerLogic, IOrderLogic
orderLogic)
{
_orderLogic = orderLogic;
var implementers = implementerLogic.ReadList(null);
if (implementers == null)
{
_logger.LogWarning("DoWork. Implementers is null");
return;
}
var orders = _orderLogic.ReadList(new OrderSearchModel
{
Status = OrderStatus.Принят
});
if (orders == null || orders.Count == 0)
{
_logger.LogWarning("DoWork. Orders is null or empty");
return;
}
_logger.LogDebug("DoWork for {Count} orders", orders.Count);
foreach (var implementer in implementers)
{
Task.Run(() => WorkerWorkAsync(implementer, orders));
}
}
/// <summary>
/// Иммитация работы исполнителя
/// </summary>
/// <param name="implementer"></param>
/// <param name="orders"></param>
private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel> orders)
{
if (_orderLogic == null || implementer == null)
{
return;
}
await RunOrderInWork(implementer);
await Task.Run(() =>
{
foreach (var order in orders)
{
try
{
_logger.LogDebug("DoWork. Worker {Id} try get order { Order}", implementer.Id, order.Id);
// пытаемся назначить заказ на исполнителя
_orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = order.Id,
ImplementerId = implementer.Id
});
// делаем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100,
1000) * order.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order{ Order} ", implementer.Id, order.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = order.Id
});
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
// кто-то мог уже перехватить заказ, игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// заканчиваем выполнение имитации в случае иной ошибки
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
});
}
/// <summary>
/// Ищем заказ, которые уже в работе (вдруг исполнителя прервали)
/// </summary>
/// <param name="implementer"></param>
/// <returns></returns>
private async Task RunOrderInWork(ImplementerViewModel implementer)
{
if (_orderLogic == null || implementer == null)
{
return;
}
try
{
var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Выполняется
}));
if (runOrder == null)
{
return;
}
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}",
implementer.Id, runOrder.Id);
// доделываем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) *
runOrder.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}",
implementer.Id, runOrder.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = runOrder.Id
});
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
// заказа может не быть, просто игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
}
}

View File

@ -0,0 +1,21 @@
using FurnitureAssemblyDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.BindingModels
{
public class ImplementerBindingModel : IImplementerModel
{
public int Id { get; set; }
public string ImplementerFIO { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public int WorkExperience { get; set; }
public int Qualification { get; set; }
}
}

View File

@ -18,5 +18,6 @@ namespace FurnitureAssemblyContracts.BindingModels
public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; }
public int ClientId { get; set; }
public int? ImplementerId { get; set; }
}
}

View File

@ -0,0 +1,20 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.BusinessLogicsContarcts
{
public interface IImplementerLogic
{
List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model);
ImplementerViewModel? ReadElement(ImplementerSearchModel model);
bool Create(ImplementerBindingModel model);
bool Update(ImplementerBindingModel model);
bool Delete(ImplementerBindingModel model);
}
}

View File

@ -11,6 +11,7 @@ namespace FurnitureAssemblyContracts.BusinessLogicsContarcts
{
public interface IOrderLogic
{
OrderViewModel? ReadElement(OrderSearchModel? model);
List<OrderViewModel>? ReadList(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);

View File

@ -0,0 +1,10 @@
namespace FurnitureAssemblyContracts.BusinessLogicsContarcts
{
public interface IWorkProcess
{
/// <summary>
/// Запуск работ
/// </summary>
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.SearchModels
{
public class ImplementerSearchModel
{
public int? Id { get; set; }
public string? ImplementerFIO { get; set; }
public string? Password { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using System;
using FurnitureAssemblyDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -12,5 +13,7 @@ namespace FurnitureAssemblyContracts.SearchModels
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public int? ClientId { get; set; }
public OrderStatus? Status { get; set; }
public int? ImplementerId { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyContracts.StoragesContracts
{
public interface IImplementerStorage
{
List<ImplementerViewModel> GetFullList();
List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model);
ImplementerViewModel? GetElement(ImplementerSearchModel model);
ImplementerViewModel? Insert(ImplementerBindingModel model);
ImplementerViewModel? Update(ImplementerBindingModel model);
ImplementerViewModel? Delete(ImplementerBindingModel model);
}
}

View File

@ -0,0 +1,23 @@
using FurnitureAssemblyDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.ViewModels
{
public class ImplementerViewModel : IImplementerModel
{
public int Id { get; set; }
[DisplayName("ФИО исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")]
public string Password { get; set; } = string.Empty;
[DisplayName("Опыт работы")]
public int WorkExperience { get; set; }
[DisplayName("Квалификация")]
public int Qualification { get; set; }
}
}

View File

@ -28,6 +28,9 @@ namespace FurnitureAssemblyContracts.ViewModels
[DisplayName("Дата создания")]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
public DateTime? DateImplement { get; set; }
public DateTime? DateImplement { get; set; }
public int? ImplementerId { get; set; }
[DisplayName("Исполнитель")]
public string? ImplementerFIO { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyDataModels.Models
{
public interface IImplementerModel : IId
{
string ImplementerFIO { get; }
string Password { get; }
int WorkExperience { get; }
int Qualification { get; }
}
}

View File

@ -15,7 +15,7 @@ namespace FurnitureAssemblyDataModels.Models
OrderStatus Status { get; }
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
int ClientId { get; }
int? ImplementerId { get; }
}
}

View File

@ -23,5 +23,6 @@ namespace FurnitureAssemblyDatabaseImplement
public virtual DbSet<FurnitureComponent> FurnitureComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
}
}

View File

@ -0,0 +1,96 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDatabaseImplement.Models;
namespace FurnitureAssemblyDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue && string.IsNullOrEmpty(model.Password))
{
return null;
}
using var context = new FurnitureAssemblyDatabase();
if (model.Id.HasValue)
{
return context.Implementers
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
}
if (model.ImplementerFIO != null && model.Password != null)
{
return context.Implementers
.FirstOrDefault(x =>
x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))
?.GetViewModel;
}
return context.Implementers
.FirstOrDefault(x =>
x.ImplementerFIO.Equals(model.ImplementerFIO))
?.GetViewModel;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return new();
}
using var context = new FurnitureAssemblyDatabase();
return context.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
public List<ImplementerViewModel> GetFullList()
{
using var context = new FurnitureAssemblyDatabase();
return context.Implementers
.Select(x => x.GetViewModel)
.ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
using var context = new FurnitureAssemblyDatabase();
context.Implementers.Add(newImplementer);
context.SaveChanges();
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var context = new FurnitureAssemblyDatabase();
var client = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
return client.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new FurnitureAssemblyDatabase();
var element = context.Implementers.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Implementers.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -17,19 +17,28 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
if (!model.Id.HasValue && (!model.ImplementerId.HasValue || !model.Status.HasValue))
{
return new();
}
using var context = new FurnitureAssemblyDatabase();
return context.Orders.Include(x => x.Furniture).Include(x => x.Client).FirstOrDefault(x =>
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
if (model.Id.HasValue)
{
return context.Orders.Include(x => x.Furniture).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x =>
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
return context.Orders
.Include(x => x.Furniture)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.ImplementerId.Equals(model.ImplementerId) && x.Status.Equals(model.Status))
?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue && (!model.DateFrom.HasValue || !model.DateTo.HasValue) && !model.ClientId.HasValue)
if (!model.Id.HasValue && (!model.DateFrom.HasValue || !model.DateTo.HasValue) && !model.ClientId.HasValue && !model.Status.HasValue)
{
return new();
}
@ -37,7 +46,7 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
if (model.Id.HasValue)
{
return context.Orders
.Include(x => x.Furniture).Include(x => x.Client)
.Include(x => x.Furniture).Include(x => x.Client).Include(x => x.Implementer)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
@ -46,8 +55,12 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
return context.Orders
.Include(x => x.Furniture)
.Include(x => x.Client)
.Where(x => !(((model.DateFrom.HasValue) && (model.DateTo.HasValue)) && !(model.DateFrom <= x.DateCreate && x.DateCreate <= model.DateTo) ||
(model.ClientId.HasValue) && !(x.ClientId.Equals(model.ClientId))))
.Include(x => x.Implementer)
.Where(x => !(
(((model.DateFrom.HasValue) && (model.DateTo.HasValue)) && !(model.DateFrom <= x.DateCreate && x.DateCreate <= model.DateTo)
|| (model.ClientId.HasValue && !x.ClientId.Equals(model.ClientId))
|| (model.Status.HasValue && !x.Status.Equals(model.Status))))
)
.Select(x => x.GetViewModel)
.ToList();
}
@ -58,6 +71,7 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
return context.Orders
.Include(x => x.Furniture)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Select(x => x.GetViewModel)
.ToList();
}
@ -72,7 +86,7 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
}
context.Orders.Add(newOrder);
context.SaveChanges();
return context.Orders.Include(x => x.Furniture).Include(x => x.Client).FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel;
return context.Orders.Include(x => x.Furniture).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
@ -85,7 +99,7 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
}
order.Update(model);
context.SaveChanges();
return context.Orders.Include(x => x.Furniture).Include(x => x.Client).FirstOrDefault(x => x.Id == order.Id)?.GetViewModel;
return context.Orders.Include(x => x.Furniture).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == order.Id)?.GetViewModel;
}
public OrderViewModel? Delete(OrderBindingModel model)
@ -96,7 +110,7 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
{
context.Orders.Remove(order);
context.SaveChanges();
return context.Orders.Include(x => x.Furniture).Include(x => x.Client).FirstOrDefault(x => x.Id == order.Id)?.GetViewModel;
return context.Orders.Include(x => x.Furniture).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == order.Id)?.GetViewModel;
}
return null;
}

View File

@ -0,0 +1,252 @@
// <auto-generated />
using System;
using FurnitureAssemblyDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace FurnitureAssemblyDatabaseImplement.Migrations
{
[DbContext(typeof(FurnitureAssemblyDatabase))]
[Migration("20230409125743_ImplementerLab6")]
partial class ImplementerLab6
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Furniture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("FurnitureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Furnitures");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.FurnitureComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("FurnitureId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("FurnitureId");
b.ToTable("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("FurnitureId")
.HasColumnType("int");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("FurnitureId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.FurnitureComponent", b =>
{
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Component", "Component")
.WithMany("FurnitureComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Furniture", "Furniture")
.WithMany("Components")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Furniture");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Order", b =>
{
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Client", "Client")
.WithMany()
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Furniture", "Furniture")
.WithMany("Orders")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Furniture");
b.Navigation("Implementer");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Component", b =>
{
b.Navigation("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Furniture", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,67 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FurnitureAssemblyDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class ImplementerLab6 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "ImplementerId",
table: "Orders",
type: "int",
nullable: true);
migrationBuilder.CreateTable(
name: "Implementers",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ImplementerFIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false),
WorkExperience = table.Column<int>(type: "int", nullable: false),
Qualification = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Implementers", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
migrationBuilder.AddForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
table: "Orders",
column: "ImplementerId",
principalTable: "Implementers",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
table: "Orders");
migrationBuilder.DropTable(
name: "Implementers");
migrationBuilder.DropIndex(
name: "IX_Orders_ImplementerId",
table: "Orders");
migrationBuilder.DropColumn(
name: "ImplementerId",
table: "Orders");
}
}
}

View File

@ -113,6 +113,33 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
b.ToTable("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -136,6 +163,9 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
b.Property<int>("FurnitureId")
.HasColumnType("int");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
@ -148,6 +178,8 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
b.HasIndex("FurnitureId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
@ -184,9 +216,15 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Furniture");
b.Navigation("Implementer");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Component", b =>
@ -200,6 +238,11 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
b.Navigation("Orders");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}

View File

@ -0,0 +1,61 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace FurnitureAssemblyDatabaseImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
[Required]
public string ImplementerFIO { get; private set; } = string.Empty;
[Required]
public string Password { get; private set; } = string.Empty;
[Required]
public int WorkExperience { get; private set; }
[Required]
public int Qualification { get; private set; }
[ForeignKey("ImplementerId")]
public virtual List<Order> Orders { get; private set; } = new();
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
ImplementerFIO = model.ImplementerFIO,
Password = model.Password,
WorkExperience = model.WorkExperience,
Qualification = model.Qualification
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
ImplementerFIO = model.ImplementerFIO;
Password = model.Password;
WorkExperience = model.WorkExperience;
Qualification = model.Qualification;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
ImplementerFIO = ImplementerFIO,
Password = Password,
WorkExperience = WorkExperience,
Qualification = Qualification
};
}
}

View File

@ -34,6 +34,10 @@ namespace FurnitureAssemblyDatabaseImplement.Models
public virtual Client Client { get; set; }
public int? ImplementerId { get; private set; }
public virtual Implementer? Implementer { get; set; }
public virtual Furniture Furniture { get; set; }
public static Order? Create(OrderBindingModel? model)
@ -51,7 +55,8 @@ namespace FurnitureAssemblyDatabaseImplement.Models
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ClientId = model.ClientId
ClientId = model.ClientId,
ImplementerId = model.ImplementerId
};
}
@ -66,7 +71,8 @@ namespace FurnitureAssemblyDatabaseImplement.Models
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ClientId = model.ClientId
ClientId = model.ClientId,
ImplementerId = model.ImplementerId
};
}
@ -79,6 +85,7 @@ namespace FurnitureAssemblyDatabaseImplement.Models
Status = model.Status;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
}
public OrderViewModel GetViewModel => new()
{
@ -91,7 +98,9 @@ namespace FurnitureAssemblyDatabaseImplement.Models
DateCreate = DateCreate,
DateImplement = DateImplement,
ClientId = ClientId,
ClientFIO = Client.ClientFIO
ClientFIO = Client.ClientFIO,
ImplementerId = ImplementerId,
ImplementerFIO = Implementer?.ImplementerFIO
};
}

View File

@ -14,12 +14,14 @@ namespace FurnitureAssemblyListImplement
public List<Order> Orders { get; set; }
public List<Furniture> Furnitures { get; set; }
public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Furnitures = new List<Furniture>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
}
public static DataListSingleton GetInstance()
{

View File

@ -0,0 +1,117 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyListImplement.Models;
namespace FurnitureAssemblyListImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataListSingleton _source;
public ImplementerStorage()
{
_source = DataListSingleton.GetInstance();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue && string.IsNullOrEmpty(model.Password))
{
return null;
}
foreach (var impl in _source.Implementers)
{
if (model.Id.HasValue && impl.Id == model.Id)
{
return impl.GetViewModel;
}
if (model.ImplementerFIO != null && model.Password != null
&& impl.ImplementerFIO.Equals(model.ImplementerFIO) && impl.Password.Equals(model.Password))
{
return impl.GetViewModel;
}
if (model.ImplementerFIO != null && impl.ImplementerFIO.Equals(model.ImplementerFIO))
{
return impl.GetViewModel;
}
}
return null;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
var result = new List<ImplementerViewModel>();
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return result;
}
foreach (var impl in _source.Implementers)
{
if (impl.ImplementerFIO.Contains(model.ImplementerFIO))
{
result.Add(impl.GetViewModel);
}
}
return result;
}
public List<ImplementerViewModel> GetFullList()
{
var result = new List<ImplementerViewModel>();
foreach (var component in _source.Implementers)
{
result.Add(component.GetViewModel);
}
return result;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = 1;
foreach (var impl in _source.Implementers)
{
if (model.Id <= impl.Id)
{
model.Id = impl.Id + 1;
}
}
var newImpl = Implementer.Create(model);
if (newImpl == null)
{
return null;
}
_source.Implementers.Add(newImpl);
return newImpl.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
foreach (var impl in _source.Implementers)
{
if (impl.Id == model.Id)
{
impl.Update(model);
return impl.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
for (int i = 0; i < _source.Implementers.Count; ++i)
{
if (_source.Implementers[i].Id == model.Id)
{
var element = _source.Implementers[i];
_source.Implementers.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -34,7 +34,7 @@ namespace FurnitureAssemblyListImplement.Implements
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
if (!model.Id.HasValue && (!model.ImplementerId.HasValue || !model.Status.HasValue))
{
return null;
}
@ -42,6 +42,9 @@ namespace FurnitureAssemblyListImplement.Implements
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
{
return GetOrderViewModel(order);
} else if (order.ImplementerId.Equals(model.ImplementerId) && order.Status.Equals(model.Status))
{
return GetOrderViewModel(order);
}
@ -51,7 +54,7 @@ namespace FurnitureAssemblyListImplement.Implements
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue && (!model.DateFrom.HasValue || !model.DateTo.HasValue))
if (!model.Id.HasValue && (!model.DateFrom.HasValue || !model.DateTo.HasValue) && !model.ClientId.HasValue && !model.Status.HasValue)
{
return new();
}
@ -70,8 +73,9 @@ namespace FurnitureAssemblyListImplement.Implements
}
foreach (var order in _source.Orders)
{
if (!(((model.DateFrom.HasValue) && (model.DateTo.HasValue)) && !(model.DateFrom <= order.DateCreate && order.DateCreate <= model.DateTo) ||
(model.ClientId.HasValue) && !(order.ClientId.Equals(model.ClientId))))
if (!(((model.DateFrom.HasValue) && (model.DateTo.HasValue)) && !(model.DateFrom <= order.DateCreate && order.DateCreate <= model.DateTo)
|| ((model.ClientId.HasValue) && !(order.ClientId.Equals(model.ClientId)))
|| ((model.Status.HasValue) && !(order.Status.Equals(model.Status)))))
{
result.Add(GetOrderViewModel(order));
}

View File

@ -0,0 +1,59 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyListImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
public static Implementer? Create(ImplementerBindingModel? model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
ImplementerFIO = model.ImplementerFIO,
Password = model.Password,
WorkExperience = model.WorkExperience,
Qualification = model.Qualification
};
}
public void Update(ImplementerBindingModel? model)
{
if (model == null)
{
return;
}
ImplementerFIO = model.ImplementerFIO;
Password = model.Password;
WorkExperience = model.WorkExperience;
Qualification = model.Qualification;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
ImplementerFIO = ImplementerFIO,
Password = Password,
WorkExperience = WorkExperience,
Qualification = Qualification
};
}
}

View File

@ -30,6 +30,8 @@ namespace FurnitureAssemblyListImplement.Models
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
@ -45,7 +47,8 @@ namespace FurnitureAssemblyListImplement.Models
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ClientId = model.ClientId
ClientId = model.ClientId,
ImplementerId = model.ImplementerId
};
}
@ -57,7 +60,8 @@ namespace FurnitureAssemblyListImplement.Models
}
Status = model.Status;
DateImplement = model.DateImplement;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
}
public OrderViewModel GetViewModel => new()
@ -69,7 +73,8 @@ namespace FurnitureAssemblyListImplement.Models
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
ClientId = ClientId
ClientId = ClientId,
ImplementerId = ImplementerId
};
}
}

View File

@ -0,0 +1,104 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Enums;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace FurnitureAssemblyRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ImplementerController : Controller
{
private readonly ILogger _logger;
private readonly IOrderLogic _order;
private readonly IImplementerLogic _logic;
public ImplementerController(IOrderLogic order, IImplementerLogic logic,
ILogger<ImplementerController> logger)
{
_logger = logger;
_order = order;
_logic = logic;
}
[HttpGet]
public ImplementerViewModel? Login(string login, string password)
{
try
{
return _logic.ReadElement(new ImplementerSearchModel
{
ImplementerFIO = login,
Password = password
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка авторизации сотрудника");
throw;
}
}
[HttpGet]
public List<OrderViewModel>? GetNewOrders()
{
try
{
return _order.ReadList(new OrderSearchModel
{
Status = OrderStatus.Принят
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения новых заказов");
throw;
}
}
[HttpGet]
public OrderViewModel? GetImplementerOrder(int implementerId)
{
try
{
return _order.ReadElement(new OrderSearchModel
{
ImplementerId = implementerId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения текущего заказа исполнителя");
throw;
}
}
[HttpPost]
public void TakeOrderInWork(OrderBindingModel model)
{
try
{
_order.TakeOrderInWork(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу",
model.Id);
throw;
}
}
[HttpPost]
public void FinishOrder(OrderBindingModel model)
{
try
{
_order.FinishOrder(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа с №{ Id}", model.Id);
throw;
}
}
}
}