Nevaeva K. A. LabWork#6 Base #6

Closed
ksenia_nevaeva wants to merge 4 commits from lab6_base into lab5_base
43 changed files with 2243 additions and 59 deletions

View File

@ -0,0 +1,173 @@
namespace TravelCompany
{
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.textBoxPassword = new System.Windows.Forms.TextBox();
this.textBoxFIO = new System.Windows.Forms.TextBox();
this.labelPassword = new System.Windows.Forms.Label();
this.labelFIO = new System.Windows.Forms.Label();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.textBoxQualification = new System.Windows.Forms.TextBox();
this.textBoxWorkExperience = new System.Windows.Forms.TextBox();
this.labelQualification = new System.Windows.Forms.Label();
this.labelWorkExpirience = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// textBoxPassword
//
this.textBoxPassword.Location = new System.Drawing.Point(122, 57);
this.textBoxPassword.Margin = new System.Windows.Forms.Padding(2);
this.textBoxPassword.Name = "textBoxPassword";
this.textBoxPassword.Size = new System.Drawing.Size(381, 27);
this.textBoxPassword.TabIndex = 9;
//
// textBoxFIO
//
this.textBoxFIO.Location = new System.Drawing.Point(122, 11);
this.textBoxFIO.Margin = new System.Windows.Forms.Padding(2);
this.textBoxFIO.Name = "textBoxFIO";
this.textBoxFIO.Size = new System.Drawing.Size(381, 27);
this.textBoxFIO.TabIndex = 8;
//
// labelPassword
//
this.labelPassword.AutoSize = true;
this.labelPassword.Location = new System.Drawing.Point(56, 57);
this.labelPassword.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.labelPassword.Name = "labelPassword";
this.labelPassword.Size = new System.Drawing.Size(62, 20);
this.labelPassword.TabIndex = 7;
this.labelPassword.Text = "Пароль";
//
// labelFIO
//
this.labelFIO.AutoSize = true;
this.labelFIO.Location = new System.Drawing.Point(76, 14);
this.labelFIO.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.labelFIO.Name = "labelFIO";
this.labelFIO.Size = new System.Drawing.Size(42, 20);
this.labelFIO.TabIndex = 6;
this.labelFIO.Text = "ФИО";
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(413, 189);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(90, 27);
this.buttonCancel.TabIndex = 11;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(297, 189);
this.buttonSave.Margin = new System.Windows.Forms.Padding(2);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(112, 27);
this.buttonSave.TabIndex = 10;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// textBoxQualification
//
this.textBoxQualification.Location = new System.Drawing.Point(122, 141);
this.textBoxQualification.Margin = new System.Windows.Forms.Padding(2);
this.textBoxQualification.Name = "textBoxQualification";
this.textBoxQualification.Size = new System.Drawing.Size(381, 27);
this.textBoxQualification.TabIndex = 15;
//
// textBoxWorkExperience
//
this.textBoxWorkExperience.Location = new System.Drawing.Point(122, 98);
this.textBoxWorkExperience.Margin = new System.Windows.Forms.Padding(2);
this.textBoxWorkExperience.Name = "textBoxWorkExperience";
this.textBoxWorkExperience.Size = new System.Drawing.Size(381, 27);
this.textBoxWorkExperience.TabIndex = 14;
//
// labelQualification
//
this.labelQualification.AutoSize = true;
this.labelQualification.Location = new System.Drawing.Point(7, 141);
this.labelQualification.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.labelQualification.Name = "labelQualification";
this.labelQualification.Size = new System.Drawing.Size(111, 20);
this.labelQualification.TabIndex = 13;
this.labelQualification.Text = "Квалификация";
//
// labelWorkExpirience
//
this.labelWorkExpirience.AutoSize = true;
this.labelWorkExpirience.Location = new System.Drawing.Point(72, 98);
this.labelWorkExpirience.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.labelWorkExpirience.Name = "labelWorkExpirience";
this.labelWorkExpirience.Size = new System.Drawing.Size(46, 20);
this.labelWorkExpirience.TabIndex = 12;
this.labelWorkExpirience.Text = "Опыт";
//
// FormImplementer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(514, 227);
this.Controls.Add(this.textBoxQualification);
this.Controls.Add(this.textBoxWorkExperience);
this.Controls.Add(this.labelQualification);
this.Controls.Add(this.labelWorkExpirience);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxPassword);
this.Controls.Add(this.textBoxFIO);
this.Controls.Add(this.labelPassword);
this.Controls.Add(this.labelFIO);
this.Name = "FormImplementer";
this.Text = "Исполнитель";
this.Load += new System.EventHandler(this.FormImplementer_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxPassword;
private TextBox textBoxFIO;
private Label labelPassword;
private Label labelFIO;
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxQualification;
private TextBox textBoxWorkExperience;
private Label labelQualification;
private Label labelWorkExpirience;
}
}

View File

@ -0,0 +1,109 @@
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;
using TravelCompanyContracts.SearchModels;
using Microsoft.Extensions.Logging;
using TravelCompanyContracts.BusinessLogicsContracts;
using TravelCompanyContracts.BindingModels;
namespace TravelCompany
{
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;
textBoxWorkExperience.Text = view.WorkExperience.ToString();
textBoxQualification.Text = view.Qualification.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
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;
}
if (string.IsNullOrEmpty(textBoxWorkExperience.Text))
{
MessageBox.Show("Заполните опыт работы", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxQualification.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(textBoxWorkExperience.Text),
Qualification = Convert.ToInt32(textBoxQualification.Text)
};
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);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

View File

@ -0,0 +1,124 @@
namespace TravelCompany
{
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.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();
this.dataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(552, 196);
this.buttonRef.Margin = new System.Windows.Forms.Padding(2);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(90, 27);
this.buttonRef.TabIndex = 9;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.buttonRef_Click);
//
// buttonDel
//
this.buttonDel.Location = new System.Drawing.Point(552, 129);
this.buttonDel.Margin = new System.Windows.Forms.Padding(2);
this.buttonDel.Name = "buttonDel";
this.buttonDel.Size = new System.Drawing.Size(90, 27);
this.buttonDel.TabIndex = 8;
this.buttonDel.Text = "Удалить";
this.buttonDel.UseVisualStyleBackColor = true;
this.buttonDel.Click += new System.EventHandler(this.buttonDel_Click);
//
// buttonUpd
//
this.buttonUpd.Location = new System.Drawing.Point(552, 69);
this.buttonUpd.Margin = new System.Windows.Forms.Padding(2);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(90, 27);
this.buttonUpd.TabIndex = 7;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.buttonUpd_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(552, 11);
this.buttonAdd.Margin = new System.Windows.Forms.Padding(2);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(90, 27);
this.buttonAdd.TabIndex = 6;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// dataGridView
//
this.dataGridView.BackgroundColor = System.Drawing.Color.White;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(11, 11);
this.dataGridView.Margin = new System.Windows.Forms.Padding(2);
this.dataGridView.MultiSelect = false;
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersVisible = false;
this.dataGridView.RowHeadersWidth = 62;
this.dataGridView.RowTemplate.Height = 33;
this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView.Size = new System.Drawing.Size(522, 424);
this.dataGridView.TabIndex = 5;
//
// FormImplementers
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(657, 446);
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 Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,109 @@
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;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.BusinessLogicsContracts;
namespace TravelCompany
{
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

@ -38,11 +38,13 @@
this.списокУсловийToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.условияПоПоездкамToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.списокЗаказовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
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.исполнителиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
@ -52,7 +54,7 @@
this.dataGridView.BackgroundColor = System.Drawing.Color.White;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(3, 36);
this.dataGridView.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.dataGridView.Margin = new System.Windows.Forms.Padding(2);
this.dataGridView.MultiSelect = false;
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersVisible = false;
@ -67,7 +69,8 @@
this.menuStrip.ImageScalingSize = new System.Drawing.Size(24, 24);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.справочникиToolStripMenuItem,
this.отчетToolStripMenuItem});
this.отчетToolStripMenuItem,
this.запускРаботToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Padding = new System.Windows.Forms.Padding(5, 2, 0, 2);
@ -80,7 +83,8 @@
this.справочникиToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.условияToolStripMenuItem,
this.путешествияToolStripMenuItem,
this.клиентыToolStripMenuItem});
this.клиентыToolStripMenuItem,
this.исполнителиToolStripMenuItem});
this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(117, 24);
this.справочникиToolStripMenuItem.Text = "Справочники";
@ -88,21 +92,21 @@
// условияToolStripMenuItem
//
this.условияToolStripMenuItem.Name = "условияToolStripMenuItem";
this.условияToolStripMenuItem.Size = new System.Drawing.Size(182, 26);
this.условияToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.условияToolStripMenuItem.Text = "Условия";
this.условияToolStripMenuItem.Click += new System.EventHandler(this.условияToolStripMenuItem_Click);
//
// путешествияToolStripMenuItem
//
this.путешествияToolStripMenuItem.Name = "путешествияToolStripMenuItem";
this.путешествияToolStripMenuItem.Size = new System.Drawing.Size(182, 26);
this.путешествияToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.путешествияToolStripMenuItem.Text = "Путешествия";
this.путешествияToolStripMenuItem.Click += new System.EventHandler(this.путешествияToolStripMenuItem_Click);
//
// клиентыToolStripMenuItem
//
this.клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
this.клиентыToolStripMenuItem.Size = new System.Drawing.Size(182, 26);
this.клиентыToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.клиентыToolStripMenuItem.Text = "Клиенты";
this.клиентыToolStripMenuItem.Click += new System.EventHandler(this.клиентыToolStripMenuItem_Click);
//
@ -137,10 +141,17 @@
this.списокЗаказовToolStripMenuItem.Text = "Список заказов";
this.списокЗаказовToolStripMenuItem.Click += new System.EventHandler(this.OrdersToolStripMenuItem_Click);
//
// запускРаботToolStripMenuItem
//
this.запускРаботToolStripMenuItem.Name = апускРаботToolStripMenuItem";
this.запускРаботToolStripMenuItem.Size = new System.Drawing.Size(114, 24);
this.запускРаботToolStripMenuItem.Text = "Запуск работ";
this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click);
//
// buttonCreateOrder
//
this.buttonCreateOrder.Location = new System.Drawing.Point(1224, 36);
this.buttonCreateOrder.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.buttonCreateOrder.Margin = new System.Windows.Forms.Padding(2);
this.buttonCreateOrder.Name = "buttonCreateOrder";
this.buttonCreateOrder.Size = new System.Drawing.Size(173, 27);
this.buttonCreateOrder.TabIndex = 2;
@ -151,7 +162,7 @@
// ButtonTakeOrderInWork
//
this.ButtonTakeOrderInWork.Location = new System.Drawing.Point(1224, 91);
this.ButtonTakeOrderInWork.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.ButtonTakeOrderInWork.Margin = new System.Windows.Forms.Padding(2);
this.ButtonTakeOrderInWork.Name = "ButtonTakeOrderInWork";
this.ButtonTakeOrderInWork.Size = new System.Drawing.Size(173, 27);
this.ButtonTakeOrderInWork.TabIndex = 3;
@ -162,7 +173,7 @@
// ButtonOrderReady
//
this.ButtonOrderReady.Location = new System.Drawing.Point(1224, 154);
this.ButtonOrderReady.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.ButtonOrderReady.Margin = new System.Windows.Forms.Padding(2);
this.ButtonOrderReady.Name = "ButtonOrderReady";
this.ButtonOrderReady.Size = new System.Drawing.Size(173, 27);
this.ButtonOrderReady.TabIndex = 4;
@ -173,7 +184,7 @@
// ButtonIssuedOrder
//
this.ButtonIssuedOrder.Location = new System.Drawing.Point(1224, 206);
this.ButtonIssuedOrder.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.ButtonIssuedOrder.Margin = new System.Windows.Forms.Padding(2);
this.ButtonIssuedOrder.Name = "ButtonIssuedOrder";
this.ButtonIssuedOrder.Size = new System.Drawing.Size(173, 27);
this.ButtonIssuedOrder.TabIndex = 5;
@ -184,7 +195,7 @@
// ButtonRef
//
this.ButtonRef.Location = new System.Drawing.Point(1224, 262);
this.ButtonRef.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.ButtonRef.Margin = new System.Windows.Forms.Padding(2);
this.ButtonRef.Name = "ButtonRef";
this.ButtonRef.Size = new System.Drawing.Size(173, 27);
this.ButtonRef.TabIndex = 6;
@ -192,6 +203,13 @@
this.ButtonRef.UseVisualStyleBackColor = true;
this.ButtonRef.Click += new System.EventHandler(this.ButtonRef_Click);
//
// исполнителиToolStripMenuItem
//
this.исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
this.исполнителиToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.исполнителиToolStripMenuItem.Text = "Исполнители";
this.исполнителиToolStripMenuItem.Click += new System.EventHandler(this.исполнителиToolStripMenuItem_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
@ -205,7 +223,7 @@
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.Margin = new System.Windows.Forms.Padding(2);
this.Name = "FormMain";
this.Text = "Туристическая фирма";
this.Load += new System.EventHandler(this.FormMain_Load);
@ -234,5 +252,7 @@
private ToolStripMenuItem условияПоПоездкамToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
}
}

View File

@ -11,12 +11,14 @@ namespace TravelCompany
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{
InitializeComponent();
_reportLogic = reportLogic;
_logger = logger;
_orderLogic = orderLogic;
_workProcess = workProcess;
}
private void FormMain_Load(object sender, EventArgs e)
{
@ -33,6 +35,7 @@ namespace TravelCompany
dataGridView.DataSource = list;
dataGridView.Columns["TravelId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["TravelName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
@ -187,5 +190,23 @@ namespace TravelCompany
form.ShowDialog();
}
}
private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic
)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
}
}

View File

@ -39,11 +39,14 @@ namespace TravelCompany
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<ITravelStorage, TravelStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IConditionLogic, ConditionLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ITravelLogic, TravelLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormCondition>();
services.AddTransient<FormConditions>();
@ -54,6 +57,8 @@ namespace TravelCompany
services.AddTransient<FormReportTravelConditions>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormClients>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();

View File

@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.BusinessLogicsContracts;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.StoragesContracts;
using TravelCompanyContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace TravelCompanyBusinessLogic.BusinessLogic
{
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. Id:{Id}. ImplementerFIO:{ImplementerFIO}. " +
"Password:{Password}", model.Id, model.ImplementerFIO, model.Password);
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. Id:{Id}. ImplementerFIO:{ImplementerFIO}." +
" Password:{Password}", model?.Id, model?.ImplementerFIO, model?.Password);
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 ArgumentNullException("Опыт работы не может быть меньше 0 лет!", nameof(model.WorkExperience));
}
if (model.Qualification < 0)
{
throw new ArgumentNullException("Квалификация не может быть меньше 0 лет!", nameof(model.Qualification));
}
_logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}." +
" Password:{Password}. Id:{Id}", model.ImplementerFIO, model.Password, model.Id);
var element = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = model.ImplementerFIO
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Исполнитель с таким ФИО уже зарегестрирован!");
}
}
}
}

View File

@ -17,6 +17,7 @@ namespace TravelCompanyBusinessLogic.BusinessLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
static readonly object _lock = new object();
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{
_logger = logger;
@ -76,6 +77,7 @@ namespace TravelCompanyBusinessLogic.BusinessLogic
throw new InvalidOperationException("Статус заказа 'Готов' может быть присвоен только заказам со статусом 'Выполняется'!");
}
model.Status = OrderStatus.Готов;
model.DateImplement = DateTime.Now;
_orderStorage.Update(model);
return true;
}
@ -93,26 +95,47 @@ namespace TravelCompanyBusinessLogic.BusinessLogic
return list;
}
public bool TakeOrderInWork(OrderBindingModel model)
public OrderViewModel? ReadElement(OrderSearchModel? model)
{
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel
if (model == null)
{
Id = model.Id
});
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ImplementerId:{ImplementerId}. OrderStatus:{OrderStatus}. Id:{Id}", model.ImplementerId, model.OrderStatus, model.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("Read operation failed");
return false;
_logger.LogWarning("ReadElement element not found");
return null;
}
if (element.Status != OrderStatus.Принят)
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
lock (_lock)
{
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Статус заказа 'Выполняется' может быть присвоен только заказам со статусом 'Принят'!");
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel
{
Id = model.Id
});
if (element == null)
{
_logger.LogWarning("Read operation failed");
return false;
}
if (element.Status != OrderStatus.Принят)
{
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Заказ должен быть переведен " +
"в статус принятого перед его выполнением!");
}
model.Status = OrderStatus.Выполняется;
_orderStorage.Update(model);
return true;
}
model.Status = OrderStatus.Выполняется;
_orderStorage.Update(model);
return true;
}
private void CheckModel(OrderBindingModel model, bool withParams = true)

View File

@ -0,0 +1,151 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.BusinessLogicsContracts;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.ViewModels;
using TravelCompanyDataModels.Enums;
namespace TravelCompanyBusinessLogic.BusinessLogic
{
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 { OrderStatus = 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 || orders == null)
{
return;
}
await RunOrderInWork(implementer);
if (orders == null || orders.Count == 0)
return;
await Task.Run(async () =>
{
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
});
// делаем работу
await Task.Delay(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
});
}
// кто-то мог уже перехватить заказ, игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// заканчиваем выполнение имитации в случае иной ошибки
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
// отдыхаем
await Task.Delay(implementer.Qualification * _rnd.Next(10, 100));
}
});
}
/// <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,
OrderStatus = OrderStatus.Выполняется
}));
if (runOrder == null)
{
return;
}
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id);
// доделываем работу
await Task.Delay(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
});
// отдыхаем
await Task.Delay(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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyDataModels.Models;
namespace TravelCompanyContracts.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 TravelCompanyContracts.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,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.ViewModels;
namespace TravelCompanyContracts.BusinessLogicsContracts
{
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

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

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TravelCompanyContracts.BusinessLogicsContracts
{
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 TravelCompanyContracts.SearchModels
{
public class ImplementerSearchModel
{
public int? Id { get; set; }
public string? ImplementerFIO { get; set; }
public string? Password { get; set; }
}
}

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyDataModels.Enums;
namespace TravelCompanyContracts.SearchModels
{
@ -12,5 +13,7 @@ namespace TravelCompanyContracts.SearchModels
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public int? ClientId { get; set; }
public int? ImplementerId { get; set; }
public OrderStatus? OrderStatus { get; set; }
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.ViewModels;
namespace TravelCompanyContracts.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 System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyDataModels.Models;
namespace TravelCompanyContracts.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

@ -21,6 +21,9 @@ namespace TravelCompanyContracts.ViewModels
public int Count { get; set; }
[DisplayName("Сумма")]
public double Sum { get; set; }
public int? ImplementerId { get; set; }
[DisplayName("ФИО Исполнителя")]
public string? ImplementerFIO { get; set; }
[DisplayName("ФИО клиента")]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Статус")]

View File

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

View File

@ -16,5 +16,6 @@ namespace TravelCompanyDataModels.Models
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
int ClientId { get; }
int? ImplementerId { get; }
}
}

View File

@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.StoragesContracts;
using TravelCompanyContracts.ViewModels;
using TravelCompanyDatabaseImplement.Models;
namespace TravelCompanyDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new TravelCompanyDatabase();
var element = context.Implementers.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Implementers.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) &&
!model.Id.HasValue && string.IsNullOrEmpty(model.Password))
{
return null;
}
using var context = new TravelCompanyDatabase();
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 TravelCompanyDatabase();
return context.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
public List<ImplementerViewModel> GetFullList()
{
using var context = new TravelCompanyDatabase();
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 TravelCompanyDatabase();
context.Implementers.Add(newImplementer);
context.SaveChanges();
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var context = new TravelCompanyDatabase();
var implementer = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (implementer == null)
{
return null;
}
implementer.Update(model);
context.SaveChanges();
return implementer.GetViewModel;
}
}
}

View File

@ -17,21 +17,30 @@ namespace TravelCompanyDatabaseImplement.Implements
public List<OrderViewModel> GetFullList()
{
using var context = new TravelCompanyDatabase();
return context.Orders.Include(x => x.Client)
return context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.Select(x => AccessTravelStorage(x.GetViewModel, context))
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.ClientId.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue)
if (!model.ClientId.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue
&& !model.OrderStatus.HasValue)
{
return new();
}
if (model.DateFrom.HasValue && model.DateTo.HasValue)
if (model.OrderStatus.HasValue)
{
using var context = new TravelCompanyDatabase();
return context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.Where(x => x.Status == model.OrderStatus)
.Select(x => AccessTravelStorage(x.GetViewModel, context))
.ToList();
}
else if (model.DateFrom.HasValue && model.DateTo.HasValue)
{
using var context = new TravelCompanyDatabase();
return context.Orders.Include(x => x.Client)
return context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => AccessTravelStorage(x.GetViewModel, context))
.ToList();
@ -39,7 +48,7 @@ namespace TravelCompanyDatabaseImplement.Implements
if (model.ClientId.HasValue)
{
using var context = new TravelCompanyDatabase();
return context.Orders.Include(x => x.Client)
return context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.Where(x => x.ClientId == model.ClientId)
.Select(x => AccessTravelStorage(x.GetViewModel, context))
.ToList();
@ -47,7 +56,7 @@ namespace TravelCompanyDatabaseImplement.Implements
else
{
using var context = new TravelCompanyDatabase();
return context.Orders.Include(x => x.Client)
return context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.Where(x => x.Id == model.Id)
.Select(x => AccessTravelStorage(x.GetViewModel, context))
.ToList();
@ -56,15 +65,24 @@ namespace TravelCompanyDatabaseImplement.Implements
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
if (!model.Id.HasValue && !model.ImplementerId.HasValue && !model.OrderStatus.HasValue)
{
return new();
}
using var context = new TravelCompanyDatabase();
return AccessTravelStorage(context.Orders.Include(x => x.Client)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel, context);
if (!model.Id.HasValue)
{
return AccessTravelStorage(context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.FirstOrDefault(x => model.ImplementerId.HasValue && model.OrderStatus.HasValue
&& x.Status == model.OrderStatus && x.ImplementerId == model.ImplementerId)
?.GetViewModel, context);
}
else
{
return AccessTravelStorage(context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel, context);
}
}
public OrderViewModel? Insert(OrderBindingModel model)
{
@ -86,7 +104,7 @@ namespace TravelCompanyDatabaseImplement.Implements
{
return null;
}
order.Update(model);
order.Update(model, context);
context.SaveChanges();
return AccessTravelStorage(order.GetViewModel, context);
}

View File

@ -0,0 +1,245 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using TravelCompanyDatabaseImplement;
#nullable disable
namespace TravelCompanyDatabaseImplement.Migrations
{
[DbContext(typeof(TravelCompanyDatabase))]
[Migration("20230515055249_UpdLab6")]
partial class UpdLab6
{
/// <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("TravelCompanyDatabaseImplement.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("TravelCompanyDatabaseImplement.Models.Condition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ConditionName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Conditions");
});
modelBuilder.Entity("TravelCompanyDatabaseImplement.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("TravelCompanyDatabaseImplement.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?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.Property<int>("TravelId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("TravelId");
b.ToTable("Orders");
});
modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Travel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("TravelName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Travels");
});
modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.TravelCondition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ConditionId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("TravelId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ConditionId");
b.HasIndex("TravelId");
b.ToTable("TravelConditions");
});
modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Order", b =>
{
b.HasOne("TravelCompanyDatabaseImplement.Models.Client", "Client")
.WithMany()
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("TravelCompanyDatabaseImplement.Models.Implementer", "Implementer")
.WithMany()
.HasForeignKey("ImplementerId");
b.HasOne("TravelCompanyDatabaseImplement.Models.Travel", "Travel")
.WithMany()
.HasForeignKey("TravelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Travel");
});
modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.TravelCondition", b =>
{
b.HasOne("TravelCompanyDatabaseImplement.Models.Condition", "Condition")
.WithMany("TravelConditions")
.HasForeignKey("ConditionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("TravelCompanyDatabaseImplement.Models.Travel", "Travel")
.WithMany("Conditions")
.HasForeignKey("TravelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Condition");
b.Navigation("Travel");
});
modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Condition", b =>
{
b.Navigation("TravelConditions");
});
modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Travel", b =>
{
b.Navigation("Conditions");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,67 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace TravelCompanyDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class UpdLab6 : 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

@ -67,6 +67,33 @@ namespace TravelCompanyDatabaseImplement.Migrations
b.ToTable("Conditions");
});
modelBuilder.Entity("TravelCompanyDatabaseImplement.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("TravelCompanyDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -87,6 +114,9 @@ namespace TravelCompanyDatabaseImplement.Migrations
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
@ -100,6 +130,8 @@ namespace TravelCompanyDatabaseImplement.Migrations
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("TravelId");
b.ToTable("Orders");
@ -159,6 +191,10 @@ namespace TravelCompanyDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("TravelCompanyDatabaseImplement.Models.Implementer", "Implementer")
.WithMany()
Review

Связь настроена не до конца

Связь настроена не до конца
.HasForeignKey("ImplementerId");
b.HasOne("TravelCompanyDatabaseImplement.Models.Travel", "Travel")
.WithMany()
.HasForeignKey("TravelId")
@ -167,6 +203,8 @@ namespace TravelCompanyDatabaseImplement.Migrations
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Travel");
});

View File

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.ViewModels;
using TravelCompanyDataModels.Models;
namespace TravelCompanyDatabaseImplement.Models
{
public class Implementer : IImplementerModel
{
[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; }
public int Id { 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

@ -29,6 +29,8 @@ namespace TravelCompanyDatabaseImplement.Models
[Required]
public int ClientId { get; set; }
public virtual Client Client { get; set; } = new();
public int? ImplementerId { get; set; }
public virtual Implementer? Implementer { get; set; } = new();
public static Order? Create(OrderBindingModel? model, TravelCompanyDatabase context)
{
@ -47,15 +49,20 @@ namespace TravelCompanyDatabaseImplement.Models
DateImplement = model.DateImplement,
ClientId = model.ClientId,
Client = context.Clients.First(x => x.Id == model.ClientId),
ImplementerId = model.ImplementerId,
Implementer = model.ImplementerId.HasValue ?
context.Implementers.First(x => x.Id == model.ImplementerId) : null,
};
}
public void Update(OrderBindingModel? model)
public void Update(OrderBindingModel? model, TravelCompanyDatabase context)
{
if (model == null)
{
return;
}
Status = model.Status;
if (model.ImplementerId.HasValue) ImplementerId = model.ImplementerId;
if (model.ImplementerId.HasValue) Implementer = context.Implementers.First(x => x.Id == model.ImplementerId);
if (model.DateImplement.HasValue) DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
@ -69,6 +76,8 @@ namespace TravelCompanyDatabaseImplement.Models
DateImplement = DateImplement,
ClientId = ClientId,
ClientFIO = Client.ClientFIO,
ImplementerId = ImplementerId,
ImplementerFIO = Implementer?.ImplementerFIO
};
}

View File

@ -24,5 +24,6 @@ namespace TravelCompanyDatabaseImplement
public virtual DbSet<TravelCondition> TravelConditions { 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

@ -16,11 +16,13 @@ namespace TravelCompanyFileImplement
private readonly string OrderFileName = "Order.xml";
private readonly string ProductFileName = "Product.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
public List<Condition> Conditions { get; private set; }
public List<Order> Orders { get; private set; }
public List<Travel> Travels { get; private set; }
public List<Client> Clients { get; private set; }
public static DataFileSingleton GetInstance()
public List<Implementer> Implementers { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
@ -32,12 +34,14 @@ namespace TravelCompanyFileImplement
public void SaveTravels() => SaveData(Travels, ProductFileName, "Travels", 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()
{
Conditions = LoadData(ConditionFileName, "Condition", x => Condition.Create(x)!)!;
Travels = LoadData(ProductFileName, "Travel", x => Travel.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,103 @@
using DocumentFormat.OpenXml.Bibliography;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.StoragesContracts;
using TravelCompanyContracts.ViewModels;
using TravelCompanyFileImplement.Models;
namespace TravelCompanyFileImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataFileSingleton _source;
public ImplementerStorage()
{
_source = DataFileSingleton.GetInstance();
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var element = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
_source.Implementers.Remove(element);
_source.SaveConditions();
return element.GetViewModel;
}
return null;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue &&
string.IsNullOrEmpty(model.Password))
{
return null;
}
if (model.ImplementerFIO != null && model.Password != null)
{
return _source.Implementers
.FirstOrDefault(x =>
x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))
?.GetViewModel;
}
if (model.Id.HasValue)
{
return _source.Implementers
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.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.SaveConditions();
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.SaveConditions();
return implementer.GetViewModel;
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using DocumentFormat.OpenXml.Bibliography;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
@ -29,14 +30,14 @@ namespace TravelCompanyFileImplement.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.OrderStatus.HasValue)
{
return new();
}
if (model.ClientId.HasValue)
{
if (model.OrderStatus.HasValue)
{
return _source.Orders
.Where(x => x.ClientId == model.ClientId)
.Where(x => x.ImplementerId == model.ImplementerId)
.Select(x => InsertTravelName(x.GetViewModel))
.ToList();
}
@ -54,17 +55,27 @@ namespace TravelCompanyFileImplement.Implements
.Select(x => InsertTravelName(x.GetViewModel))
.ToList();
}
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
if (!model.Id.HasValue && !model.ImplementerId.HasValue && !model.OrderStatus.HasValue)
{
return null;
}
return InsertTravelName(_source.Orders
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel);
if (!model.Id.HasValue)
{
return InsertTravelName(_source.Orders
.FirstOrDefault(x => model.ImplementerId.HasValue && model.OrderStatus.HasValue
&& x.ImplementerId == model.ImplementerId && x.Status == model.OrderStatus)
?.GetViewModel);
}
else
{
return InsertTravelName(_source.Orders
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel);
}
}
public OrderViewModel? Insert(OrderBindingModel model)
{

View File

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.ViewModels;
using TravelCompanyDataModels.Models;
namespace TravelCompanyFileImplement.Models
{
public class Implementer : IImplementerModel
{
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 int Id { 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

@ -22,6 +22,7 @@ namespace TravelCompanyFileImplement.Models
public DateTime DateCreate { get; set; }
public DateTime? DateImplement { get; set; }
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public static Order? Create(OrderBindingModel model)
{
if (model == null)
@ -38,6 +39,7 @@ namespace TravelCompanyFileImplement.Models
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
};
}
public static Order? Create(XElement element)
@ -57,6 +59,7 @@ namespace TravelCompanyFileImplement.Models
DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value)
? null : Convert.ToDateTime(element.Element("DateImplement")!.Value),
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value),
};
}
public void Update(OrderBindingModel model)
@ -66,6 +69,7 @@ namespace TravelCompanyFileImplement.Models
return;
}
Status = model.Status;
ImplementerId = model.ImplementerId;
if (model.DateImplement.HasValue) { DateImplement = model.DateImplement; }
}
public OrderViewModel GetViewModel => new()
@ -78,6 +82,7 @@ namespace TravelCompanyFileImplement.Models
DateCreate = DateCreate,
DateImplement = DateImplement,
ClientId = ClientId,
ImplementerId = ImplementerId,
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
@ -87,7 +92,8 @@ namespace TravelCompanyFileImplement.Models
new XElement("Status", ((int)Status).ToString()),
new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString(),
new XElement("ClientId", ClientId)));
new XElement("ClientId", ClientId)),
new XElement("ImplementerId", ImplementerId.ToString()));
}
}

View File

@ -15,12 +15,14 @@ namespace TravelCompanyListImplement
public List<Order> Orders { get; set; }
public List<Travel> Travels { get; set; }
public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
private DataListSingleton()
{
Conditions = new List<Condition>();
Orders = new List<Order>();
Travels = new List<Travel>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
}
public static DataListSingleton GetInstance()
{

View File

@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.StoragesContracts;
using TravelCompanyContracts.ViewModels;
using TravelCompanyListImplement.Models;
namespace TravelCompanyListImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataListSingleton _source;
public ImplementerStorage()
{
_source = DataListSingleton.GetInstance();
}
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;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue
&& string.IsNullOrEmpty(model.Password))
{
return null;
}
foreach (var implementer in _source.Implementers)
{
if (model.Id.HasValue && implementer.Id == model.Id)
{
return implementer.GetViewModel;
}
if (model.ImplementerFIO != null && model.Password != null
&& implementer.ImplementerFIO.Equals(model.ImplementerFIO) &&
implementer.Password.Equals(model.Password))
{
return implementer.GetViewModel;
}
if (model.ImplementerFIO != null && implementer.ImplementerFIO.Equals(model.ImplementerFIO))
{
return implementer.GetViewModel;
}
}
return null;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
var result = new List<ImplementerViewModel>();
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return result;
}
foreach (var implementer in _source.Implementers)
{
if (implementer.ImplementerFIO.Contains(model.ImplementerFIO))
{
result.Add(implementer.GetViewModel);
}
}
return result;
}
public List<ImplementerViewModel> GetFullList()
{
var result = new List<ImplementerViewModel>();
foreach (var implementer in _source.Implementers)
{
result.Add(implementer.GetViewModel);
}
return result;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = 1;
foreach (var implementer in _source.Implementers)
{
if (model.Id <= implementer.Id)
{
model.Id = implementer.Id + 1;
}
}
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
_source.Implementers.Add(newImplementer);
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
foreach (var implementer in _source.Implementers)
{
if (implementer.Id == model.Id)
{
implementer.Update(model);
return implementer.GetViewModel;
}
}
return null;
}
}
}

View File

@ -30,21 +30,21 @@ namespace TravelCompanyListImplement.Implements
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue)
if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.OrderStatus.HasValue)
{
return result;
}
if (model.ClientId.HasValue)
if (model.ImplementerId.HasValue && model.OrderStatus.HasValue)
{
foreach (var order in _source.Orders)
{
if (order.ClientId == model.ClientId)
if (order.Status == model.OrderStatus)
{
result.Add(InsertTravelName(order.GetViewModel));
}
}
}
if (!model.DateFrom.HasValue || !model.DateTo.HasValue)
else if (!model.DateFrom.HasValue || !model.DateTo.HasValue)
{
foreach (var order in _source.Orders)
{
@ -68,15 +68,29 @@ namespace TravelCompanyListImplement.Implements
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
if (!model.Id.HasValue && !model.ImplementerId.HasValue && !model.OrderStatus.HasValue)
{
return null;
}
foreach (var order in _source.Orders)
if (!model.Id.HasValue)
{
if (model.Id.HasValue && order.Id == model.Id)
foreach (var order in _source.Orders)
{
return InsertTravelName(order.GetViewModel);
if (model.ImplementerId.HasValue && model.OrderStatus.HasValue
&& order.ImplementerId == model.ImplementerId && order.Status == model.OrderStatus)
{
return InsertTravelName(order.GetViewModel);
}
}
}
else
{
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
{
return InsertTravelName(order.GetViewModel);
}
}
}
return null;

View File

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.ViewModels;
using TravelCompanyDataModels.Models;
namespace TravelCompanyListImplement.Models
{
public class Implementer : IImplementerModel
{
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 int Id { 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

@ -22,6 +22,7 @@ namespace TravelCompanyListImplement.Models
public DateTime DateCreate { get; set; }
public DateTime? DateImplement { get; set; }
public int ClientId { get; set; }
public int? ImplementerId { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
@ -38,6 +39,7 @@ namespace TravelCompanyListImplement.Models
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
};
}
public void Update(OrderBindingModel? model)
@ -47,6 +49,8 @@ namespace TravelCompanyListImplement.Models
return;
}
Status = model.Status;
DateCreate = model.DateCreate;
ImplementerId = model.ImplementerId;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
@ -59,6 +63,7 @@ namespace TravelCompanyListImplement.Models
DateCreate = DateCreate,
DateImplement = DateImplement,
ClientId = ClientId,
ImplementerId = ImplementerId,
};
}
}

View File

@ -0,0 +1,103 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using Microsoft.AspNetCore.Mvc;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.BusinessLogicsContracts;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.ViewModels;
using TravelCompanyDataModels.Enums;
namespace TravelCompanyRestApi.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
{
OrderStatus = 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;
}
}
}
}