PIbd-23. Leonteva V.A. Lab work 06 #7

Closed
leonteva.v wants to merge 3 commits from Lab_6 into Lab_5
44 changed files with 2411 additions and 462 deletions

View File

@ -25,7 +25,22 @@ namespace LawFirmView
_logicO = logicO;
_clientLogic = clientLogic;
_list = logicD.ReadList(null);
}
if (_list != null)
{
comboBoxDocument.DisplayMember = "PastryName";
comboBoxDocument.ValueMember = "Id";
comboBoxDocument.DataSource = _list;
comboBoxDocument.SelectedItem = null;
}
var clients = _clientLogic.ReadList(null);
if (clients != null)
{
comboBoxClient.DisplayMember = "clientFIO";
comboBoxClient.ValueMember = "Id";
comboBoxClient.DataSource = clients;
comboBoxClient.SelectedItem = null;
}
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка документов для заказа");

View File

@ -0,0 +1,173 @@
namespace LawFirmView
{
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()
{
label1 = new Label();
label2 = new Label();
label3 = new Label();
label4 = new Label();
textBoxFio = new TextBox();
textBoxPassword = new TextBox();
numericUpDownWorkExperience = new NumericUpDown();
numericUpDownQualification = new NumericUpDown();
buttonCancel = new Button();
buttonSave = new Button();
((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownQualification).BeginInit();
SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(79, 12);
label1.Name = "label1";
label1.Size = new Size(37, 15);
label1.TabIndex = 0;
label1.Text = "ФИО:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(69, 41);
label2.Name = "label2";
label2.Size = new Size(52, 15);
label2.TabIndex = 1;
label2.Text = "Пароль:";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(78, 68);
label3.Name = "label3";
label3.Size = new Size(38, 15);
label3.TabIndex = 2;
label3.Text = "Стаж:";
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(25, 97);
label4.Name = "label4";
label4.Size = new Size(91, 15);
label4.TabIndex = 3;
label4.Text = "Квалификация:";
//
// textBoxFio
//
textBoxFio.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxFio.Location = new Point(127, 9);
textBoxFio.Name = "textBoxFio";
textBoxFio.Size = new Size(271, 23);
textBoxFio.TabIndex = 4;
//
// textBoxPassword
//
textBoxPassword.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxPassword.Location = new Point(127, 38);
textBoxPassword.Name = "textBoxPassword";
textBoxPassword.PasswordChar = '*';
textBoxPassword.Size = new Size(271, 23);
textBoxPassword.TabIndex = 5;
//
// numericUpDownWorkExperience
//
numericUpDownWorkExperience.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
numericUpDownWorkExperience.Location = new Point(127, 66);
numericUpDownWorkExperience.Name = "numericUpDownWorkExperience";
numericUpDownWorkExperience.Size = new Size(271, 23);
numericUpDownWorkExperience.TabIndex = 6;
//
// numericUpDownQualification
//
numericUpDownQualification.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
numericUpDownQualification.Location = new Point(127, 95);
numericUpDownQualification.Name = "numericUpDownQualification";
numericUpDownQualification.Size = new Size(271, 23);
numericUpDownQualification.TabIndex = 7;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(309, 138);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(89, 33);
buttonCancel.TabIndex = 8;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonSave.Location = new Point(214, 138);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(89, 33);
buttonSave.TabIndex = 9;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// FormImplementer
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(410, 183);
Controls.Add(buttonSave);
Controls.Add(buttonCancel);
Controls.Add(numericUpDownQualification);
Controls.Add(numericUpDownWorkExperience);
Controls.Add(textBoxPassword);
Controls.Add(textBoxFio);
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Name = "FormImplementer";
Text = "Добавление / Редактирование исполнителя";
Load += FormImplementer_Load;
((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownQualification).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private Label label3;
private Label label4;
private TextBox textBoxFio;
private TextBox textBoxPassword;
private NumericUpDown numericUpDownWorkExperience;
private NumericUpDown numericUpDownQualification;
private Button buttonCancel;
private Button buttonSave;
}
}

View File

@ -0,0 +1,97 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicsContracts;
using LawFirmContracts.SearchModels;
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
namespace LawFirmView
{
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;
numericUpDownQualification.Value = view.Qualification;
numericUpDownWorkExperience.Value = view.WorkExperience;
}
}
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(textBoxPassword.Text))
{
MessageBox.Show("Заполните пароль", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxFio.Text))
{
MessageBox.Show("Заполните фио", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = textBoxFio.Text,
Password = textBoxPassword.Text,
Qualification = (int)numericUpDownQualification.Value,
WorkExperience = (int)numericUpDownWorkExperience.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);
}
}
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

@ -1,222 +1,214 @@
namespace LawFirmView
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
partial class FormMain
{
/// <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);
}
/// <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
#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()
{
menuStrip = new MenuStrip();
toolStripMenuItem = new ToolStripMenuItem();
BlanksToolStripMenuItem = new ToolStripMenuItem();
DocumentsToolStripMenuItem = new ToolStripMenuItem();
ReportsToolStripMenuItem = new ToolStripMenuItem();
ListOfDocumentsToolStripMenuItem = new ToolStripMenuItem();
FormsForDocumentsToolStripMenuItem = new ToolStripMenuItem();
OrderListToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonIssuedOrder = new Button();
buttonUpdate = new Button();
ClientsToolStripMenuItem = new ToolStripMenuItem();
menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, ReportsToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(929, 28);
menuStrip.TabIndex = 0;
menuStrip.Text = "Справочники";
//
// toolStripMenuItem
//
toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { BlanksToolStripMenuItem, DocumentsToolStripMenuItem, ClientsToolStripMenuItem });
toolStripMenuItem.Name = "toolStripMenuItem";
toolStripMenuItem.Size = new Size(117, 24);
toolStripMenuItem.Text = "Справочники";
//
// BlanksToolStripMenuItem
//
BlanksToolStripMenuItem.Name = "BlanksToolStripMenuItem";
BlanksToolStripMenuItem.Size = new Size(224, 26);
BlanksToolStripMenuItem.Text = "Бланки";
BlanksToolStripMenuItem.Click += BlanksToolStripMenuItem_Click;
//
// DocumentsToolStripMenuItem
//
DocumentsToolStripMenuItem.Name = "DocumentsToolStripMenuItem";
DocumentsToolStripMenuItem.Size = new Size(224, 26);
DocumentsToolStripMenuItem.Text = "Документы";
DocumentsToolStripMenuItem.Click += DocumentsToolStripMenuItem_Click;
//
// ReportsToolStripMenuItem
//
ReportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ListOfDocumentsToolStripMenuItem, FormsForDocumentsToolStripMenuItem, OrderListToolStripMenuItem });
ReportsToolStripMenuItem.Name = "ReportsToolStripMenuItem";
ReportsToolStripMenuItem.Size = new Size(73, 24);
ReportsToolStripMenuItem.Text = "Отчеты";
//
// ListOfDocumentsToolStripMenuItem
//
ListOfDocumentsToolStripMenuItem.Name = "ListOfDocumentsToolStripMenuItem";
ListOfDocumentsToolStripMenuItem.Size = new Size(252, 26);
ListOfDocumentsToolStripMenuItem.Text = "Список документов";
ListOfDocumentsToolStripMenuItem.Click += ListOfDocumentsToolStripMenuItem_Click;
//
// FormsForDocumentsToolStripMenuItem
//
FormsForDocumentsToolStripMenuItem.Name = "FormsForDocumentsToolStripMenuItem";
FormsForDocumentsToolStripMenuItem.Size = new Size(252, 26);
FormsForDocumentsToolStripMenuItem.Text = "Бланки по документам";
FormsForDocumentsToolStripMenuItem.Click += FormsForDocumentsToolStripMenuItem_Click;
//
// OrderListToolStripMenuItem
//
OrderListToolStripMenuItem.Name = "OrderListToolStripMenuItem";
OrderListToolStripMenuItem.Size = new Size(252, 26);
OrderListToolStripMenuItem.Text = "Список заказов";
OrderListToolStripMenuItem.Click += OrderListToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 31);
dataGridView.Margin = new Padding(3, 4, 3, 4);
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(714, 606);
dataGridView.TabIndex = 1;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(732, 42);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(185, 29);
buttonCreateOrder.TabIndex = 2;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += buttonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(732, 86);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(185, 29);
buttonTakeOrderInWork.TabIndex = 3;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click;
//
// buttonOrderReady
//
buttonOrderReady.Location = new Point(732, 132);
buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(185, 29);
buttonOrderReady.TabIndex = 4;
buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += buttonOrderReady_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(732, 177);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(185, 29);
buttonIssuedOrder.TabIndex = 5;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += buttonIssuedOrder_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(732, 221);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(185, 29);
buttonUpdate.TabIndex = 6;
buttonUpdate.Text = "Обновить список";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += buttonUpdate_Click;
//
// ClientsToolStripMenuItem
//
ClientsToolStripMenuItem.Name = "ClientsToolStripMenuItem";
ClientsToolStripMenuItem.Size = new Size(224, 26);
ClientsToolStripMenuItem.Text = "Клиенты";
ClientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(929, 649);
Controls.Add(buttonUpdate);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormMain";
Text = "Юридическая фирма";
Load += FormMain_Load;
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
menuStrip = new MenuStrip();
toolStripMenuItem = new ToolStripMenuItem();
BlanksToolStripMenuItem = new ToolStripMenuItem();
DocumentsToolStripMenuItem = new ToolStripMenuItem();
ClientsToolStripMenuItem = new ToolStripMenuItem();
ImplementersToolStripMenuItem = new ToolStripMenuItem();
ReportsToolStripMenuItem = new ToolStripMenuItem();
ListOfDocumentsToolStripMenuItem = new ToolStripMenuItem();
FormsForDocumentsToolStripMenuItem = new ToolStripMenuItem();
OrderListToolStripMenuItem = new ToolStripMenuItem();
StartWorksToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonIssuedOrder = new Button();
buttonUpdate = new Button();
menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, ReportsToolStripMenuItem, StartWorksToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(929, 28);
menuStrip.TabIndex = 0;
menuStrip.Text = "Справочники";
//
// toolStripMenuItem
//
toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { BlanksToolStripMenuItem, DocumentsToolStripMenuItem, ClientsToolStripMenuItem, ImplementersToolStripMenuItem });
toolStripMenuItem.Name = "toolStripMenuItem";
toolStripMenuItem.Size = new Size(117, 24);
toolStripMenuItem.Text = "Справочники";
//
// BlanksToolStripMenuItem
//
BlanksToolStripMenuItem.Name = "BlanksToolStripMenuItem";
BlanksToolStripMenuItem.Size = new Size(185, 26);
BlanksToolStripMenuItem.Text = "Бланки";
BlanksToolStripMenuItem.Click += BlanksToolStripMenuItem_Click;
//
// DocumentsToolStripMenuItem
//
DocumentsToolStripMenuItem.Name = "DocumentsToolStripMenuItem";
DocumentsToolStripMenuItem.Size = new Size(185, 26);
DocumentsToolStripMenuItem.Text = "Документы";
DocumentsToolStripMenuItem.Click += DocumentsToolStripMenuItem_Click;
//
// ClientsToolStripMenuItem
//
ClientsToolStripMenuItem.Name = "ClientsToolStripMenuItem";
ClientsToolStripMenuItem.Size = new Size(185, 26);
ClientsToolStripMenuItem.Text = "Клиенты";
ClientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
//
// ImplementersToolStripMenuItem
//
ImplementersToolStripMenuItem.Name = "ImplementersToolStripMenuItem";
ImplementersToolStripMenuItem.Size = new Size(185, 26);
ImplementersToolStripMenuItem.Text = "Исполнители";
ImplementersToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click;
//
// ReportsToolStripMenuItem
//
ReportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ListOfDocumentsToolStripMenuItem, FormsForDocumentsToolStripMenuItem, OrderListToolStripMenuItem });
ReportsToolStripMenuItem.Name = "ReportsToolStripMenuItem";
ReportsToolStripMenuItem.Size = new Size(73, 24);
ReportsToolStripMenuItem.Text = "Отчеты";
//
// ListOfDocumentsToolStripMenuItem
//
ListOfDocumentsToolStripMenuItem.Name = "ListOfDocumentsToolStripMenuItem";
ListOfDocumentsToolStripMenuItem.Size = new Size(252, 26);
ListOfDocumentsToolStripMenuItem.Text = "Список документов";
ListOfDocumentsToolStripMenuItem.Click += ListOfDocumentsToolStripMenuItem_Click;
//
// FormsForDocumentsToolStripMenuItem
//
FormsForDocumentsToolStripMenuItem.Name = "FormsForDocumentsToolStripMenuItem";
FormsForDocumentsToolStripMenuItem.Size = new Size(252, 26);
FormsForDocumentsToolStripMenuItem.Text = "Бланки по документам";
FormsForDocumentsToolStripMenuItem.Click += FormsForDocumentsToolStripMenuItem_Click;
//
// OrderListToolStripMenuItem
//
OrderListToolStripMenuItem.Name = "OrderListToolStripMenuItem";
OrderListToolStripMenuItem.Size = new Size(252, 26);
OrderListToolStripMenuItem.Text = "Список заказов";
OrderListToolStripMenuItem.Click += OrderListToolStripMenuItem_Click;
//
// StartWorksToolStripMenuItem
//
StartWorksToolStripMenuItem.Name = "StartWorksToolStripMenuItem";
StartWorksToolStripMenuItem.Size = new Size(114, 24);
StartWorksToolStripMenuItem.Text = "Запуск работ";
StartWorksToolStripMenuItem.Click += StartWorksToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 31);
dataGridView.Margin = new Padding(3, 4, 3, 4);
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(714, 606);
dataGridView.TabIndex = 1;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(732, 42);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(185, 29);
buttonCreateOrder.TabIndex = 2;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += buttonCreateOrder_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(732, 103);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(185, 29);
buttonIssuedOrder.TabIndex = 5;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += buttonIssuedOrder_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(732, 164);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(185, 29);
buttonUpdate.TabIndex = 6;
buttonUpdate.Text = "Обновить список";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += buttonUpdate_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(929, 649);
Controls.Add(buttonUpdate);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormMain";
Text = "Юридическая фирма";
Load += FormMain_Load;
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
#endregion
private MenuStrip menuStrip;
private ToolStripMenuItem toolStripMenuItem;
private ToolStripMenuItem BlanksToolStripMenuItem;
private ToolStripMenuItem DocumentsToolStripMenuItem;
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonUpdate;
private ToolStripMenuItem ReportsToolStripMenuItem;
private ToolStripMenuItem ListOfDocumentsToolStripMenuItem;
private ToolStripMenuItem FormsForDocumentsToolStripMenuItem;
private ToolStripMenuItem OrderListToolStripMenuItem;
private ToolStripMenuItem ClientsToolStripMenuItem;
}
private MenuStrip menuStrip;
private ToolStripMenuItem toolStripMenuItem;
private ToolStripMenuItem BlanksToolStripMenuItem;
private ToolStripMenuItem DocumentsToolStripMenuItem;
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonIssuedOrder;
private Button buttonUpdate;
private ToolStripMenuItem ReportsToolStripMenuItem;
private ToolStripMenuItem ListOfDocumentsToolStripMenuItem;
private ToolStripMenuItem FormsForDocumentsToolStripMenuItem;
private ToolStripMenuItem OrderListToolStripMenuItem;
private ToolStripMenuItem ClientsToolStripMenuItem;
private ToolStripMenuItem StartWorksToolStripMenuItem;
private ToolStripMenuItem ImplementersToolStripMenuItem;
}
}

View File

@ -8,201 +8,218 @@ using LawFirmContracts.BusinessLogicContracts;
namespace LawFirmView
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["DocumentId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
}
_logger.LogInformation("Загрузка прошла успешно");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void buttonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = id,
DocumentId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["DocumentId"].Value),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString())
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void buttonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel
{
Id = id,
DocumentId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["DocumentId"].Value),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString())
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonIssuedOrder_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new
OrderBindingModel
{
Id = id,
DocumentId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["DocumentId"].Value),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString())
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
LoadData();
}
private void BlanksToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormBlanks));
if (service is FormBlanks form)
{
form.ShowDialog();
}
}
private void DocumentsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDocuments));
if (service is FormDocuments form)
{
form.ShowDialog();
}
}
private void ListOfDocumentsToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveDocumentsToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void FormsForDocumentsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportDocumentBlanks));
if (service is FormReportDocumentBlanks form)
{
form.ShowDialog();
}
}
private void OrderListToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrder));
if (service is FormReportOrder form)
{
form.ShowDialog();
}
}
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormViewClients));
if (service is FormViewClients form)
{
form.ShowDialog();
}
}
}
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["DocumentId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
}
_logger.LogInformation("Загрузка прошла успешно");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void buttonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = id,
DocumentId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["DocumentId"].Value),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString())
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void buttonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel
{
Id = id,
DocumentId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["DocumentId"].Value),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString())
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonIssuedOrder_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new
OrderBindingModel
{
Id = id,
DocumentId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["DocumentId"].Value),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString())
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
LoadData();
}
private void BlanksToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormBlanks));
if (service is FormBlanks form)
{
form.ShowDialog();
}
}
private void DocumentsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDocuments));
if (service is FormDocuments form)
{
form.ShowDialog();
}
}
private void ListOfDocumentsToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveDocumentsToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void FormsForDocumentsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportDocumentBlanks));
if (service is FormReportDocumentBlanks form)
{
form.ShowDialog();
}
}
private void OrderListToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrder));
if (service is FormReportOrder form)
{
form.ShowDialog();
}
}
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormViewClients));
if (service is FormViewClients form)
{
form.ShowDialog();
}
}
private void StartWorksToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormViewImplementers));
if (service is FormViewImplementers form)
{
form.ShowDialog();
}
}
}
}

View File

@ -0,0 +1,126 @@
namespace LawFirmView
{
partial class FormViewImplementers
{
/// <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()
{
buttonRef = new Button();
buttonDel = new Button();
buttonUpd = new Button();
buttonAdd = new Button();
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// buttonRef
//
buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonRef.Location = new Point(447, 279);
buttonRef.Margin = new Padding(3, 4, 3, 4);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(103, 49);
buttonRef.TabIndex = 9;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// buttonDel
//
buttonDel.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonDel.Location = new Point(447, 211);
buttonDel.Margin = new Padding(3, 4, 3, 4);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(103, 44);
buttonDel.TabIndex = 8;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonUpd
//
buttonUpd.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonUpd.Location = new Point(447, 145);
buttonUpd.Margin = new Padding(3, 4, 3, 4);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(103, 45);
buttonUpd.TabIndex = 7;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
//
// buttonAdd
//
buttonAdd.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonAdd.Location = new Point(447, 85);
buttonAdd.Margin = new Padding(3, 4, 3, 4);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(103, 40);
buttonAdd.TabIndex = 6;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridView
//
dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(14, 16);
dataGridView.Margin = new Padding(3, 4, 3, 4);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(392, 403);
dataGridView.TabIndex = 5;
//
// FormViewImplementers
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(585, 425);
Controls.Add(buttonRef);
Controls.Add(buttonDel);
Controls.Add(buttonUpd);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Margin = new Padding(3, 4, 3, 4);
Name = "FormViewImplementers";
Text = "Просмотр списка исполнителей";
Load += FormViewImplementers_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

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

View File

@ -40,14 +40,17 @@ namespace LawFirmView
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IDocumentStorage, DocumentStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IBlankLogic, BlankLogic>();
services.AddTransient<IBlankLogic, BlankLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IDocumentLogic, DocumentLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
@ -61,6 +64,8 @@ namespace LawFirmView
services.AddTransient<FormReportDocumentBlanks>();
services.AddTransient<FormReportOrder>();
services.AddTransient<FormViewClients>();
}
services.AddTransient<FormViewImplementers>();
services.AddTransient<FormImplementer>();
}
}
}

View File

@ -0,0 +1,123 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicsContracts;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StoragesContracts;
using LawFirmContracts.ViewModels;
using LawFirmDataModel.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmBusinessLogic.BusinessLogics
{
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. FIO:{FIO}.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. FIO:{FIO}.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 (model.WorkExperience < 0)
{
throw new ArgumentException("Опыт работы не должен быть отрицательным", nameof(model.WorkExperience));
}
if (model.Qualification < 0)
{
throw new ArgumentException("Квалификация не должна быть отрицательной", nameof(model.Qualification));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля исполнителя", nameof(model.ImplementerFIO));
}
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
throw new ArgumentNullException("Нет фио исполнителя", nameof(model.ImplementerFIO));
}
_logger.LogInformation("Implementer. Id: {Id}, FIO: {FIO}", model.Id, model.ImplementerFIO);
var element = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = model.ImplementerFIO,
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Исполнитель с таким фио уже есть");
}
}
}
}

View File

@ -5,6 +5,8 @@ using LawFirmContracts.StoragesContracts;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Enums;
using Microsoft.Extensions.Logging;
using DocumentFormat.OpenXml.EMMA;
using LawFirmContracts.BindingModels;
namespace LawFirmBusinessLogic.BusinessLogics
{
@ -12,6 +14,7 @@ namespace LawFirmBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
static readonly object _locker = new object();
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{
_logger = logger;
@ -47,12 +50,18 @@ namespace LawFirmBusinessLogic.BusinessLogics
return false;
}
model.Status = newStatus;
model.DateCreate = viewModel.DateCreate;
if (model.Status == OrderStatus.Готов) model.DateImplement = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
else
{
model.DateImplement = viewModel.DateImplement;
}
CheckModel(model, false);
if (viewModel.ImplementerId.HasValue)
model.ImplementerId = viewModel.ImplementerId;
model.DocumentId = viewModel.DocumentId;
model.Sum = viewModel.Sum;
model.Count = viewModel.Count;
CheckModel(model);
if (_orderStorage.Update(model) == null)
{
model.Status--;
@ -71,7 +80,10 @@ namespace LawFirmBusinessLogic.BusinessLogics
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выполняется);
lock (_locker)
{
return StatusUpdate(model, OrderStatus.Выполняется);
}
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
@ -86,6 +98,22 @@ namespace LawFirmBusinessLogic.BusinessLogics
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Id:{ Id}", model.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)

View File

@ -0,0 +1,146 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicsContracts;
using LawFirmContracts.SearchModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmBusinessLogic.BusinessLogics
{
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)
{
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
});
}
// кто-то мог уже перехватить заказ, игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// заканчиваем выполнение имитации в случае иной ошибки
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
// отдыхаем
Thread.Sleep(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);
// доделываем работу
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,19 @@
using LawFirmDataModel.Models;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.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

@ -8,7 +8,8 @@ namespace LawFirmContracts.BindingModels
public int Id { get; set; }
public int DocumentId { get; set; }
public int ClientId { get; set; }
public int Count { get; set; }
public int? ImplementerId { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);

View File

@ -0,0 +1,20 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.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

@ -7,6 +7,7 @@ namespace LawFirmContracts.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 LawFirmContracts.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 LawFirmContracts.SearchModels
{
public class ImplementerSearchModel
{
public int? Id { get; set; }
public string? ImplementerFIO { get; set; }
public string? Password { get; set; }
}
}

View File

@ -1,4 +1,6 @@
namespace LawFirmContracts.SearchModels
using LawFirmDataModels.Enums;
namespace LawFirmContracts.SearchModels
{
public class OrderSearchModel
{
@ -6,5 +8,7 @@
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,21 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.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,27 @@
using LawFirmDataModel.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.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

@ -9,11 +9,14 @@ namespace LawFirmContracts.ViewModels
[DisplayName("Номер")]
public int Id { get; set; }
public int DocumentId { get; set; }
public int? ImplementerId { get; set; }
[DisplayName("Документ")]
public int ClientId { get; set; }
[DisplayName("Данные клиента")]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Документ")]
[DisplayName("Фамилия исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Документ")]
public string DocumentName { get; set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }

View File

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

View File

@ -11,5 +11,6 @@ namespace LawFirmDataModels.Models
OrderStatus Status { get; }
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
int? ImplementerId { get; }
}
}

View File

@ -0,0 +1,90 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StoragesContracts;
using LawFirmContracts.ViewModels;
using LawFirmDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new LawFirmDatabase();
var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
context.Implementers.Remove(res);
context.SaveChanges();
}
return res?.GetViewModel;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
using var context = new LawFirmDatabase();
if (model.Id.HasValue)
return context.Implementers.FirstOrDefault(x => 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;
if (model.ImplementerFIO != null)
return context.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel;
return null;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.ImplementerFIO != null) // На случай если фио не будет уникальным (по заданию оно уникально)
{
using var context = new LawFirmDatabase();
return context.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public List<ImplementerViewModel> GetFullList()
{
using var context = new LawFirmDatabase();
return context.Implementers.Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
using var context = new LawFirmDatabase();
var res = Implementer.Create(model);
if (res != null)
{
context.Implementers.Add(res);
context.SaveChanges();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var context = new LawFirmDatabase();
var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
context.SaveChanges();
}
return res?.GetViewModel;
}
}
}

View File

@ -11,12 +11,26 @@ namespace LawFirmDatabaseImplement.Implements
{
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new LawFirmDatabase();
return context.Orders.Include(x => x.Document).Include(x => x.Client).FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
if (model.Id.HasValue)
{
return context.Orders
.Include(x => x.Document)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
if (model.ImplementerId.HasValue && model.OrderStatus.HasValue)
{
return context.Orders
.Include(x => x.Document)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.ImplementerId == model.ImplementerId && x.Status == model.OrderStatus)
?.GetViewModel;
}
return null;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
@ -48,7 +62,17 @@ namespace LawFirmDatabaseImplement.Implements
.Select(x => x.GetViewModel)
.ToList();
}
else
else if (model.OrderStatus.HasValue)
{
return context.Orders
.Include(x => x.Document)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.Status == model.OrderStatus)
.Select(x => x.GetViewModel)
.ToList();
}
else
{
return new();
}
@ -56,7 +80,7 @@ namespace LawFirmDatabaseImplement.Implements
public List<OrderViewModel> GetFullList()
{
using var context = new LawFirmDatabase();
return context.Orders.Include(x => x.Document).Include(x => x.Client).Select(x => x.GetViewModel).ToList();
return context.Orders.Include(x => x.Document).Include(x => x.Client).Include(x => x.Implementer).Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
@ -73,19 +97,19 @@ namespace LawFirmDatabaseImplement.Implements
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new LawFirmDatabase();
var order = context.Orders.Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id);
var order = context.Orders.Include(x => x.Client).Include(x => x.Implementer).Include(x => x.Document).FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return context.Orders.Include(x => x.Document).Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
return order.GetViewModel;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new LawFirmDatabase();
var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id);
var element = context.Orders.Include(x => x.Client).Include(x => x.Implementer).Include(x => x.Document).FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
var deletedElement = context.Orders
@ -94,8 +118,8 @@ namespace LawFirmDatabaseImplement.Implements
?.GetViewModel;
context.Orders.Remove(element);
context.SaveChanges();
return deletedElement;
}
return element.GetViewModel;
}
return null;
}
}

View File

@ -9,7 +9,7 @@ namespace LawFirmDatabaseImplement
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS; Initial Catalog=LawFirmDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS; Initial Catalog=LawFirm6;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
@ -18,5 +18,6 @@ namespace LawFirmDatabaseImplement
public virtual DbSet<DocumentBlank> DocumentBlanks { 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

@ -12,8 +12,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace LawFirmDatabaseImplement.Migrations
{
[DbContext(typeof(LawFirmDatabase))]
[Migration("20240517194322_InitialCreate")]
partial class InitialCreate
[Migration("20240524144938_r")]
partial class r
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -116,6 +116,33 @@ namespace LawFirmDatabaseImplement.Migrations
b.ToTable("DocumentBlanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.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("LawFirmDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -139,6 +166,9 @@ namespace LawFirmDatabaseImplement.Migrations
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
@ -151,6 +181,8 @@ namespace LawFirmDatabaseImplement.Migrations
b.HasIndex("DocumentId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
@ -187,9 +219,15 @@ namespace LawFirmDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Document");
b.Navigation("Implementer");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b =>
@ -208,6 +246,11 @@ namespace LawFirmDatabaseImplement.Migrations
b.Navigation("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}

View File

@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations;
namespace LawFirmDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
public partial class r : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
@ -54,6 +54,22 @@ namespace LawFirmDatabaseImplement.Migrations
table.PrimaryKey("PK_Documents", x => x.Id);
});
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.CreateTable(
name: "DocumentBlanks",
columns: table => new
@ -93,6 +109,7 @@ namespace LawFirmDatabaseImplement.Migrations
Sum = table.Column<double>(type: "float", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
DateCreate = table.Column<DateTime>(type: "datetime2", nullable: false),
ImplementerId = table.Column<int>(type: "int", nullable: true),
DateImplement = table.Column<DateTime>(type: "datetime2", nullable: true)
},
constraints: table =>
@ -110,6 +127,11 @@ namespace LawFirmDatabaseImplement.Migrations
principalTable: "Documents",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
column: x => x.ImplementerId,
principalTable: "Implementers",
principalColumn: "Id");
});
migrationBuilder.CreateIndex(
@ -131,6 +153,11 @@ namespace LawFirmDatabaseImplement.Migrations
name: "IX_Orders_DocumentId",
table: "Orders",
column: "DocumentId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
}
/// <inheritdoc />
@ -150,6 +177,9 @@ namespace LawFirmDatabaseImplement.Migrations
migrationBuilder.DropTable(
name: "Documents");
migrationBuilder.DropTable(
name: "Implementers");
}
}
}

View File

@ -113,6 +113,33 @@ namespace LawFirmDatabaseImplement.Migrations
b.ToTable("DocumentBlanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.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("LawFirmDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -136,6 +163,9 @@ namespace LawFirmDatabaseImplement.Migrations
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
@ -148,6 +178,8 @@ namespace LawFirmDatabaseImplement.Migrations
b.HasIndex("DocumentId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
@ -184,9 +216,15 @@ namespace LawFirmDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Document");
b.Navigation("Implementer");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b =>
@ -205,6 +243,11 @@ namespace LawFirmDatabaseImplement.Migrations
b.Navigation("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}

View File

@ -0,0 +1,57 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModel.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmDatabaseImplement.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; }
[ForeignKey("ImplementerId")]
public virtual List<Order> Orders { get; private set; } = new();
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Id = model.Id,
Password = model.Password,
Qualification = model.Qualification,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience,
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Password = model.Password;
Qualification = model.Qualification;
ImplementerFIO = model.ImplementerFIO;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
Qualification = Qualification,
ImplementerFIO = ImplementerFIO,
WorkExperience = WorkExperience,
};
}
}

View File

@ -21,10 +21,12 @@ namespace LawFirmDatabaseImplement.Models
public OrderStatus Status { get; set; }
[Required]
public DateTime DateCreate { get; set; }
public int? ImplementerId { get; private set; }
public DateTime? DateImplement { get; set; }
public virtual Document Document { get; set; }
public virtual Client Client { get; set; }
public int Id { get; set; }
public virtual Implementer? Implementer { get; private set; }
public int Id { get; set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
@ -40,7 +42,8 @@ namespace LawFirmDatabaseImplement.Models
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
DateImplement = model.DateImplement,
ImplementerId = model.ImplementerId,
};
}
public void Update(OrderBindingModel? model)
@ -49,8 +52,14 @@ namespace LawFirmDatabaseImplement.Models
{
return;
}
DocumentId = model.DocumentId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
Id = model.Id;
}
public OrderViewModel GetViewModel => new()
{
@ -58,12 +67,14 @@ namespace LawFirmDatabaseImplement.Models
DocumentId = DocumentId,
ClientId = ClientId,
ClientFIO = Client.ClientFIO,
Count = Count,
ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
DocumentName = Document.DocumentName
DocumentName = Document.DocumentName,
ImplementerId = ImplementerId,
};
}
}

View File

@ -10,11 +10,13 @@ namespace LawFirmFileImplement
private readonly string OrderFileName = "Order.xml";
private readonly string DocumentFileName = "Document.xml";
private readonly string ClientFileName = "Client.xml";
public List<Blank> Blanks { get; private set; }
private readonly string ImplementerFileName = "Implementer.xml";
public List<Blank> Blanks { get; private set; }
public List<Order> Orders { get; private set; }
public List<Document> Documents { 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)
{
@ -26,13 +28,15 @@ namespace LawFirmFileImplement
public void SaveDocuments() => SaveData(Documents, DocumentFileName, "Documents", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement);
private DataFileSingleton()
public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement);
private DataFileSingleton()
{
Blanks = LoadData(BlankFileName, "Blank", x => Blank.Create(x)!)!;
Documents = LoadData(DocumentFileName, "Document", x => Document.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
}
Orders = new List<Order>();
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,90 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StoragesContracts;
using LawFirmContracts.ViewModels;
using LawFirmFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmFileImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataFileSingleton _source;
public ImplementerStorage()
{
_source = DataFileSingleton.GetInstance();
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
_source.Implementers.Remove(res);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (model.Id.HasValue)
return _source.Implementers.FirstOrDefault(x => 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;
if (model.ImplementerFIO != null)
return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel;
return null;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.ImplementerFIO != null) // На случай если фио не будет уникальным (по заданию оно уникально)
{
return _source.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
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 res = Implementer.Create(model);
if (res != null)
{
_source.Implementers.Add(res);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
}
}

View File

@ -33,8 +33,15 @@ namespace LawFirmFileImplement.Implements
.Select(x => x.GetViewModel)
.ToList();
}
var result = GetElement(model);
return result != null ? new() { result } : new();
if (!model.Id.HasValue && model.OrderStatus.HasValue)
{
return source.Orders
.Where(x => model.OrderStatus == x.Status)
.Select(x => x.GetViewModel)
.ToList();
}
var result = GetElement(model);
return result != null ? new() { result } : new();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
@ -42,6 +49,19 @@ namespace LawFirmFileImplement.Implements
{
return null;
}
if (model.ImplementerId.HasValue && model.OrderStatus.HasValue)
{
return source.Orders
.FirstOrDefault(x => x.ImplementerId == model.ImplementerId &&
model.OrderStatus == x.Status)
?.GetViewModel;
}
if (model.ImplementerId.HasValue)
{
return source.Orders
.FirstOrDefault(x => x.ImplementerId == model.ImplementerId)
?.GetViewModel;
}
return source.Orders.FirstOrDefault(x =>
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}

View File

@ -0,0 +1,76 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModel.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace LawFirmFileImplement.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(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
ImplementerFIO = element.Element("FIO")!.Value,
Password = element.Element("Password")!.Value,
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
Qualification = Convert.ToInt32(element.Element("Qualification")!.Value),
WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value),
};
}
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Id = model.Id,
Password = model.Password,
Qualification = model.Qualification,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience,
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Password = model.Password;
Qualification = model.Qualification;
ImplementerFIO = model.ImplementerFIO;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
Qualification = Qualification,
ImplementerFIO = ImplementerFIO,
};
public XElement GetXElement => new("Client",
new XAttribute("Id", Id),
new XElement("Password", Password),
new XElement("FIO", ImplementerFIO),
new XElement("Qualification", Qualification),
new XElement("WorkExperience", WorkExperience)
);
}
}

View File

@ -11,7 +11,8 @@ namespace LawFirmFileImplement.Models
public int Id { get; private set; }
public int DocumentId { get; private set; }
public int ClientId { get; set; }
public int Count { get; private set; }
public int? ImplementerId { get; set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
@ -32,6 +33,7 @@ namespace LawFirmFileImplement.Models
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ImplementerId = model.ImplementerId
};
}
public static Order? Create(XElement element)
@ -40,12 +42,18 @@ namespace LawFirmFileImplement.Models
{
return null;
}
var dateImplement = element.Element("DateImplement")!.Value;
var order = new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
DocumentId = Convert.ToInt32(element.Element("DocumentId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Status = (OrderStatus)Convert.ToInt32(element.Element("Status")!.Value),
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value),
DateImplement = string.IsNullOrEmpty(dateImplement) ? null : Convert.ToDateTime(dateImplement),
ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value),
};
DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl);
order.DateImplement = dateImpl;
@ -63,8 +71,14 @@ namespace LawFirmFileImplement.Models
{
return;
}
DocumentId = model.DocumentId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
ImplementerId = model.ImplementerId;
DateImplement = model.DateImplement;
Id = model.Id;
}
public OrderViewModel GetViewModel => new()
{
@ -76,6 +90,7 @@ namespace LawFirmFileImplement.Models
DateImplement = DateImplement,
Id = Id,
Status = Status,
ImplementerId = ImplementerId
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
@ -84,6 +99,7 @@ namespace LawFirmFileImplement.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("ImplementerId", ImplementerId));
}
}

View File

@ -9,13 +9,15 @@ namespace LawFirmListImplement
public List<Order> Orders { get; set; }
public List<Document> Documents { get; set; }
public List<Client> Clients { get; set; }
private DataListSingleton()
public List<Implementer> Implementers { get; set; }
private DataListSingleton()
{
Blanks = new List<Blank>();
Orders = new List<Order>();
Documents = new List<Document>();
Clients = new List<Client>();
}
Implementers = new List<Implementer>();
}
public static DataListSingleton GetInstance()
{
if (_instance == null)

View File

@ -0,0 +1,113 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StoragesContracts;
using LawFirmContracts.ViewModels;
using LawFirmListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmListImplement.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)
{
foreach (var x in _source.Implementers)
{
if (model.Id.HasValue && x.Id == model.Id)
return x.GetViewModel;
if (model.ImplementerFIO != null && model.Password != null &&
x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))
return x.GetViewModel;
if (model.ImplementerFIO != null && x.ImplementerFIO.Equals(model.ImplementerFIO))
return x.GetViewModel;
}
return null;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
// На случай если при расширении проекта фио не будет уникальным
// (по заданию оно уникально)
List<ImplementerViewModel> result = new();
if (model.ImplementerFIO != null)
{
foreach (var implementer in _source.Implementers)
{
if (implementer.ImplementerFIO.Equals(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 res = Implementer.Create(model);
if (res != null)
{
_source.Implementers.Add(res);
}
return res?.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

@ -32,10 +32,10 @@ namespace LawFirmListImplement.Implements
foreach (var order in _source.Orders)
{
if (order.Id == model.Id ||
model.DateFrom <= order.DateCreate &&
order.DateCreate <= model.DateTo ||
model.ClientId.HasValue &&
order.ClientId == model.ClientId)
model.DateFrom <= order.DateCreate && order.DateCreate <= model.DateTo ||
model.ClientId.HasValue && order.ClientId == model.ClientId ||
model.ImplementerId.HasValue && order.ImplementerId == model.ImplementerId ||
model.OrderStatus.HasValue && model.OrderStatus == order.Status)
{
result.Add(GetViewModel(order));
}
@ -50,7 +50,16 @@ namespace LawFirmListImplement.Implements
}
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
if (order.Id == model.Id)
{
return GetViewModel(order);
}
else if (model.ImplementerId.HasValue && model.OrderStatus.HasValue &&
order.ImplementerId == model.ImplementerId && model.OrderStatus == order.Status)
{
return GetViewModel(order);
}
else if (model.ImplementerId.HasValue && model.ImplementerId == order.ImplementerId)
{
return GetViewModel(order);
}

View File

@ -0,0 +1,53 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModel.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmListImplement.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()
{
Id = model.Id,
Password = model.Password,
Qualification = model.Qualification,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience,
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Password = model.Password;
Qualification = model.Qualification;
ImplementerFIO = model.ImplementerFIO;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
Qualification = Qualification,
ImplementerFIO = ImplementerFIO,
};
}
}

View File

@ -10,7 +10,8 @@ namespace LawFirmListImplement.Models
public int Id { get; private set; }
public int DocumentId { get; private set; }
public int ClientId { get; private set; }
public int Count { get; private set; }
public int? ImplementerId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
@ -30,7 +31,8 @@ namespace LawFirmListImplement.Models
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
DateImplement = model.DateImplement,
ImplementerId = model.ImplementerId,
};
}
public void Update(OrderBindingModel? model)
@ -39,8 +41,14 @@ namespace LawFirmListImplement.Models
{
return;
}
DocumentId = model.DocumentId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
Id = model.Id;
}
public OrderViewModel GetViewModel => new()
{
@ -51,7 +59,8 @@ namespace LawFirmListImplement.Models
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
DateImplement = DateImplement,
ImplementerId = ImplementerId
};
}
}

View File

@ -0,0 +1,102 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicsContracts;
using LawFirmContracts.SearchModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Enums;
using Microsoft.AspNetCore.Mvc;
namespace LawFirmRestApi.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;
}
}
}
}