This commit is contained in:
Данила Мочалов 2023-04-23 23:05:06 +04:00
commit 7a22a82042
249 changed files with 155103 additions and 246 deletions

View File

@ -17,9 +17,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LawFirmFileImplement", "Law
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LawFirmDatabaseImplement", "LawFirmDatabaseImplement\LawFirmDatabaseImplement.csproj", "{CB0444D3-5BDA-42DB-95F9-60191AE9073A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LawFirmRestApi", "LawFirmRestApi\LawFirmRestApi.csproj", "{8DB8A004-DB42-46F2-8EAA-AAEB498FCD36}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LawFirmRestApi", "LawFirmRestApi\LawFirmRestApi.csproj", "{8DB8A004-DB42-46F2-8EAA-AAEB498FCD36}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LawFirmClientApp", "LawFirmClientApp\LawFirmClientApp.csproj", "{9D63F716-C761-423B-BBC2-DC5F51081B43}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LawFirmClientApp", "LawFirmClientApp\LawFirmClientApp.csproj", "{9D63F716-C761-423B-BBC2-DC5F51081B43}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LawFirmShopApp", "LawFirmShopApp\LawFirmShopApp.csproj", "{B246B813-6218-4DD6-B48E-42D0FF5588B6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -63,6 +65,10 @@ Global
{9D63F716-C761-423B-BBC2-DC5F51081B43}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9D63F716-C761-423B-BBC2-DC5F51081B43}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9D63F716-C761-423B-BBC2-DC5F51081B43}.Release|Any CPU.Build.0 = Release|Any CPU
{B246B813-6218-4DD6-B48E-42D0FF5588B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B246B813-6218-4DD6-B48E-42D0FF5588B6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B246B813-6218-4DD6-B48E-42D0FF5588B6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B246B813-6218-4DD6-B48E-42D0FF5588B6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -38,11 +38,11 @@
this.buttonEdit = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.ID = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnBlankName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxBlanks.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
@ -148,26 +148,6 @@
this.dataGridView.TabIndex = 0;
this.dataGridView.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_CellContentClick);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(356, 379);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(155, 29);
this.buttonSave.TabIndex = 5;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(536, 379);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(155, 29);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// ID
//
this.ID.HeaderText = "ID";
@ -192,6 +172,26 @@
this.ColumnCount.Name = "ColumnCount";
this.ColumnCount.Width = 125;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(356, 379);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(155, 29);
this.buttonSave.TabIndex = 5;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(536, 379);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(155, 29);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormDocument
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);

166
LawFirm/LawFirm/FormMail.Designer.cs generated Normal file
View File

@ -0,0 +1,166 @@
namespace LawFirmView
{
partial class FormMail
{
/// <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();
textBoxHead = new TextBox();
textBoxBody = new TextBox();
buttonCancel = new Button();
buttonSave = new Button();
label3 = new Label();
labelHead = new Label();
labelBody = new Label();
labelFrom = new Label();
SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(539, 53);
label1.Name = "label1";
label1.Size = new Size(84, 20);
label1.TabIndex = 0;
label1.Text = "Заголовок:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(539, 115);
label2.Name = "label2";
label2.Size = new Size(104, 20);
label2.TabIndex = 1;
label2.Text = "Текст письма:";
//
// textBoxHead
//
textBoxHead.Location = new Point(547, 85);
textBoxHead.Name = "textBoxHead";
textBoxHead.Size = new Size(318, 27);
textBoxHead.TabIndex = 3;
//
// textBoxBody
//
textBoxBody.Location = new Point(547, 138);
textBoxBody.Name = "textBoxBody";
textBoxBody.Size = new Size(318, 27);
textBoxBody.TabIndex = 4;
//
// buttonCancel
//
buttonCancel.Location = new Point(664, 230);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(771, 230);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 6;
buttonSave.Text = "Отправить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(541, 9);
label3.Name = "label3";
label3.Size = new Size(82, 20);
label3.TabIndex = 7;
label3.Text = "Ваш ответ:";
//
// labelHead
//
labelHead.AutoSize = true;
labelHead.Location = new Point(12, 9);
labelHead.Name = "labelHead";
labelHead.Size = new Size(165, 20);
labelHead.TabIndex = 8;
labelHead.Text = "Заголовок сообщения";
//
// labelBody
//
labelBody.AutoSize = true;
labelBody.Location = new Point(12, 53);
labelBody.Name = "labelBody";
labelBody.Size = new Size(129, 20);
labelBody.TabIndex = 9;
labelBody.Text = "Текст сообщения";
//
// labelFrom
//
labelFrom.AutoSize = true;
labelFrom.Location = new Point(12, 234);
labelFrom.Name = "labelFrom";
labelFrom.Size = new Size(33, 20);
labelFrom.TabIndex = 10;
labelFrom.Text = "От: ";
//
// FormMail
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(877, 266);
Controls.Add(labelFrom);
Controls.Add(labelBody);
Controls.Add(labelHead);
Controls.Add(label3);
Controls.Add(buttonSave);
Controls.Add(buttonCancel);
Controls.Add(textBoxBody);
Controls.Add(textBoxHead);
Controls.Add(label2);
Controls.Add(label1);
Name = "FormMail";
Text = "Ответ на письмо";
Load += FormMail_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private TextBox textBoxHead;
private TextBox textBoxBody;
private Button buttonCancel;
private Button buttonSave;
private Label label3;
private Label labelHead;
private Label labelBody;
private Label labelFrom;
}
}

View File

@ -0,0 +1,81 @@
using LawFirmBusinessLogic.MailWorker;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.ViewModels;
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 FormMail : Form
{
private readonly ILogger _logger;
private readonly AbstractMailWorker _mailWorker;
private readonly IMessageInfoLogic _logic;
private MessageInfoViewModel _message;
public string MessageId { get; set; } = string.Empty;
public FormMail(ILogger<FormMail> logger, AbstractMailWorker mailWorker, IMessageInfoLogic logic)
{
InitializeComponent();
_logger = logger;
_mailWorker = mailWorker;
_logic = logic;
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void buttonSave_Click(object sender, EventArgs e)
{
_mailWorker.MailSendAsync(new()
{
MailAddress = _message.SenderName,
Subject = textBoxHead.Text,
Text = textBoxBody.Text,
});
_logic.Update(new()
{
MessageId = MessageId,
Reply = textBoxBody.Text,
IsReaded = true,
});
MessageBox.Show("Успешно отправлен ответ", "Отправлен ответ", MessageBoxButtons.OK);
DialogResult = DialogResult.OK;
Close();
}
private void FormMail_Load(object sender, EventArgs e)
{
try
{
_message = _logic.ReadElement(new() { MessageId = MessageId });
if (_message == null) throw new ArgumentNullException("Письма с таким Id не существует");
labelHead.Text = _message.Subject;
labelBody.Text = _message.Body;
labelFrom.Text = $"От: {_message.SenderName}";
if (_message.IsReaded is false)
{
_logic.Update(new() { MessageId = MessageId, IsReaded = true, Reply = _message.Reply });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения собщения");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

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

View File

@ -1,62 +1,114 @@
namespace LawFirmView
{
partial class FormMails
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
partial class FormMails
{
/// <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()
{
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(776, 426);
dataGridView.TabIndex = 0;
//
// FormMails
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridView);
Name = "FormMails";
Text = "Письма";
Load += FormMails_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
buttonPrevPage = new Button();
buttonNextPage = new Button();
labelPage = new Label();
buttonReply = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(776, 426);
dataGridView.TabIndex = 0;
//
// buttonPrevPage
//
buttonPrevPage.Location = new Point(594, 444);
buttonPrevPage.Name = "buttonPrevPage";
buttonPrevPage.Size = new Size(94, 29);
buttonPrevPage.TabIndex = 1;
buttonPrevPage.Text = "Пред.";
buttonPrevPage.UseVisualStyleBackColor = true;
buttonPrevPage.Click += buttonPrevPage_Click;
//
// buttonNextPage
//
buttonNextPage.Location = new Point(694, 444);
buttonNextPage.Name = "buttonNextPage";
buttonNextPage.Size = new Size(94, 29);
buttonNextPage.TabIndex = 2;
buttonNextPage.Text = "След.";
buttonNextPage.UseVisualStyleBackColor = true;
buttonNextPage.Click += buttonNextPage_Click;
//
// labelPage
//
labelPage.AutoSize = true;
labelPage.Location = new Point(462, 448);
labelPage.Name = "labelPage";
labelPage.Size = new Size(91, 20);
labelPage.TabIndex = 3;
labelPage.Text = "Страница: 0";
//
// buttonReply
//
buttonReply.Location = new Point(12, 444);
buttonReply.Name = "buttonReply";
buttonReply.Size = new Size(94, 29);
buttonReply.TabIndex = 4;
buttonReply.Text = "Ответить";
buttonReply.UseVisualStyleBackColor = true;
buttonReply.Click += buttonReply_Click;
//
// FormMails
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 475);
Controls.Add(buttonReply);
Controls.Add(labelPage);
Controls.Add(buttonNextPage);
Controls.Add(buttonPrevPage);
Controls.Add(dataGridView);
Name = "FormMails";
Text = "Письма";
Load += FormMails_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
#endregion
private DataGridView dataGridView;
}
private DataGridView dataGridView;
private Button buttonPrevPage;
private Button buttonNextPage;
private Label labelPage;
private Button buttonReply;
}
}

View File

@ -1,4 +1,6 @@
using LawFirmContracts.BusinessLogicContracts;
using LawFirm;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@ -12,31 +14,94 @@ using System.Windows.Forms;
namespace LawFirmView
{
public partial class FormMails : Form
{
private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic;
public partial class FormMails : Form
{
private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic;
private int currentPage = 1;
public int pageSize = 2;
public FormMails(ILogger<FormMails> logger, IMessageInfoLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
public FormMails(ILogger<FormMails> logger, IMessageInfoLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
buttonPrevPage.Enabled = false;
}
private void FormMails_Load(object sender, EventArgs e)
{
try
{
dataGridView.FillAndConfigGrid(_logic.ReadList(null));
private void FormMails_Load(object sender, EventArgs e)
{
LoadMail();
}
private bool LoadMail()
{
try
{
dataGridView.FillAndConfigGrid(_logic.ReadList(new()
{
Page = currentPage,
PageSize = pageSize,
});
_logger.LogInformation("Загрузка писем");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки писем");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
_logger.LogInformation("Загрузка писем");
labelPage.Text = $"Страница: {currentPage}";
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки писем");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return false;
}
}
private void buttonPrevPage_Click(object sender, EventArgs e)
{
if (currentPage == 1)
{
return;
}
currentPage--;
if (LoadMail())
{
buttonNextPage.Enabled = true;
if (currentPage == 1)
{
buttonPrevPage.Enabled = false;
}
}
}
private void buttonNextPage_Click(object sender, EventArgs e)
{
currentPage++;
if (!LoadMail() || ((List<MessageInfoViewModel>)dataGridView.DataSource).Count == 0)
{
currentPage--;
LoadMail();
buttonNextPage.Enabled = false;
}
else
{
buttonPrevPage.Enabled = true;
}
}
private void buttonReply_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormMail));
if (service is FormMail form)
{
form.MessageId = (string)(dataGridView.SelectedRows[0].Cells["MessageId"].Value);
form.ShowDialog();
LoadMail();
}
}
}
}
}

View File

@ -32,6 +32,7 @@
справочникиToolStripMenuItem = new ToolStripMenuItem();
бланкиToolStripMenuItem = new ToolStripMenuItem();
документыToolStripMenuItem = new ToolStripMenuItem();
магазиныToolStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem();
исполнителиToolStripMenuItem = new ToolStripMenuItem();
письмаToolStripMenuItem = new ToolStripMenuItem();
@ -39,11 +40,20 @@
списокДокументовToolStripMenuItem = new ToolStripMenuItem();
бланкиПоДокументамToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
запускРаботToolStripMenuItem = new ToolStripMenuItem();
списокМагазиновToolStripMenuItem = new ToolStripMenuItem();
документыВМагазинахToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовПоДатеToolStripMenuItem = new ToolStripMenuItem();
запускРаботыToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonSetToFinish = new Button();
buttonUpdate = new Button();
buttonSupplyShop = new Button();
buttonSellDocuments = new Button();
создатьБэкапToolStripMenuItem = new ToolStripMenuItem();
menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
@ -86,6 +96,14 @@
клиентыToolStripMenuItem.Size = new Size(185, 26);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// магазиныToolStripMenuItem
//
магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
магазиныToolStripMenuItem.Size = new Size(224, 26);
магазиныToolStripMenuItem.Text = "Магазины";
магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click;
//
// исполнителиToolStripMenuItem
//
@ -127,14 +145,34 @@
списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
списокЗаказовToolStripMenuItem.Size = new Size(252, 26);
списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click;
списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click;// списокМагазиновToolStripMenuItem
//
списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem";
списокМагазиновToolStripMenuItem.Size = new Size(259, 26);
списокМагазиновToolStripMenuItem.Text = "Список магазинов";
списокМагазиновToolStripMenuItem.Click += списокМагазиновToolStripMenuItem_Click;
//
// запускРаботToolStripMenuItem
// документыВМагазинахToolStripMenuItem
//
запускРаботToolStripMenuItem.Name = апускРаботToolStripMenuItem";
запускРаботToolStripMenuItem.Size = new Size(114, 24);
запускРаботToolStripMenuItem.Text = "Запуск работ";
запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click;
документыВМагазинахToolStripMenuItem.Name = окументыВМагазинахToolStripMenuItem";
документыВМагазинахToolStripMenuItem.Size = new Size(259, 26);
документыВМагазинахToolStripMenuItem.Text = "Документы в магазинах";
документыВМагазинахToolStripMenuItem.Click += документыВМагазинахToolStripMenuItem_Click;
//
// списокЗаказовПоДатеToolStripMenuItem
//
списокЗаказовПоДатеToolStripMenuItem.Name = "списокЗаказовПоДатеToolStripMenuItem";
списокЗаказовПоДатеToolStripMenuItem.Size = new Size(259, 26);
списокЗаказовПоДатеToolStripMenuItem.Text = "Список заказов по дате";
списокЗаказовПоДатеToolStripMenuItem.Click += списокЗаказовПоДатеToolStripMenuItem_Click;
//
// запускРаботыToolStripMenuItem
//
запускРаботыToolStripMenuItem.Name = апускРаботыToolStripMenuItem";
запускРаботыToolStripMenuItem.Size = new Size(125, 24);
запускРаботыToolStripMenuItem.Text = "Запуск работы";
запускРаботыToolStripMenuItem.Click += запускРаботыToolStripMenuItem_Click;
//
//
// dataGridView
//
@ -182,6 +220,26 @@
создатьБэкапToolStripMenuItem.Size = new Size(122, 24);
создатьБэкапToolStripMenuItem.Text = "Создать бэкап";
создатьБэкапToolStripMenuItem.Click += создатьБэкапToolStripMenuItem_Click;
buttonSupplyShop.Location = new Point(933, 115);
buttonSupplyShop.Name = "buttonSupplyShop";
buttonSupplyShop.Size = new Size(194, 29);
buttonSupplyShop.TabIndex = 7;
buttonSupplyShop.Text = "Пополнение магазина";
buttonSupplyShop.UseVisualStyleBackColor = true;
buttonSupplyShop.Click += buttonSupplyShop_Click;
//
// buttonSellDocuments
//
buttonSellDocuments.Location = new Point(933, 150);
buttonSellDocuments.Name = "buttonSellDocuments";
buttonSellDocuments.Size = new Size(194, 29);
buttonSellDocuments.TabIndex = 8;
buttonSellDocuments.Text = "Продажа документов";
buttonSellDocuments.UseVisualStyleBackColor = true;
buttonSellDocuments.Click += buttonSellDocuments_Click;
//
// FormMain
//
@ -191,6 +249,10 @@
Controls.Add(buttonUpdate);
Controls.Add(buttonSetToFinish);
Controls.Add(buttonCreateOrder);
Controls.Add(buttonSellDocuments);
Controls.Add(buttonSupplyShop);
Controls.Add(dataGridView);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
@ -220,8 +282,16 @@
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem;
private ToolStripMenuItem запускРаботыToolStripMenuItem;
private ToolStripMenuItem письмаToolStripMenuItem;
private ToolStripMenuItem создатьБэкапToolStripMenuItem;
private ToolStripMenuItem магазиныToolStripMenuItem;
private Button buttonSupplyShop;
private Button buttonSellDocuments;
private ToolStripMenuItem списокМагазиновToolStripMenuItem;
private ToolStripMenuItem документыВМагазинахToolStripMenuItem;
private ToolStripMenuItem списокЗаказовПоДатеToolStripMenuItem;
}
}

View File

@ -104,6 +104,45 @@ namespace LawFirmView
}
private void списокМагазиновToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveShopsToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void документыВМагазинахToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportShopDocuments));
if (service is FormReportShopDocuments form)
{
form.ShowDialog();
}
}
private void списокЗаказовПоДатеToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportDateOrders));
if (service is FormReportDateOrders form)
{
form.ShowDialog();
}
}
private void магазиныToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void buttonCreateOrder_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormCreateOrder>();
@ -143,12 +182,31 @@ namespace LawFirmView
LoadData();
}
private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork(DependencyManager.Instance.Resolve<IImplementerLogic>(),_orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
private void buttonSupplyShop_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShopSupply));
if (service is FormShopSupply form)
{
form.ShowDialog();
}
}
}
private void buttonSellDocuments_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShopSell));
if (service is FormShopSell form)
{
form.ShowDialog();
}
}
private void запускРаботыToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void письмаToolStripMenuItem_Click(object sender, EventArgs e)
{

View File

@ -0,0 +1,86 @@
namespace LawFirmView
{
partial class FormReportDateOrders
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel = new System.Windows.Forms.Panel();
this.buttonCreateToPdf = new System.Windows.Forms.Button();
this.buttonCreateReport = new System.Windows.Forms.Button();
this.panel.SuspendLayout();
this.SuspendLayout();
//
// panel
//
this.panel.Controls.Add(this.buttonCreateToPdf);
this.panel.Controls.Add(this.buttonCreateReport);
this.panel.Dock = System.Windows.Forms.DockStyle.Top;
this.panel.Location = new System.Drawing.Point(0, 0);
this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(978, 69);
this.panel.TabIndex = 1;
//
// buttonCreateToPdf
//
this.buttonCreateToPdf.Location = new System.Drawing.Point(769, 39);
this.buttonCreateToPdf.Name = "buttonCreateToPdf";
this.buttonCreateToPdf.Size = new System.Drawing.Size(190, 27);
this.buttonCreateToPdf.TabIndex = 5;
this.buttonCreateToPdf.Text = "PDF";
this.buttonCreateToPdf.UseVisualStyleBackColor = true;
this.buttonCreateToPdf.Click += new System.EventHandler(this.buttonCreateToPdf_Click);
//
// buttonCreateReport
//
this.buttonCreateReport.Location = new System.Drawing.Point(554, 39);
this.buttonCreateReport.Name = "buttonCreateReport";
this.buttonCreateReport.Size = new System.Drawing.Size(190, 27);
this.buttonCreateReport.TabIndex = 4;
this.buttonCreateReport.Text = "Сформировать";
this.buttonCreateReport.UseVisualStyleBackColor = true;
this.buttonCreateReport.Click += new System.EventHandler(this.buttonCreateReport_Click);
//
// FormReportDateOrders
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(978, 450);
this.Controls.Add(this.panel);
this.Name = "FormReportDateOrders";
this.Text = "Заказы по датам";
this.panel.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private Panel panel;
private Button buttonCreateToPdf;
private Button buttonCreateReport;
}
}

View File

@ -0,0 +1,79 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
using Microsoft.Reporting.WinForms;
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 FormReportDateOrders : Form
{
private readonly ReportViewer reportViewer;
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportDateOrders(ILogger<FormReportDateOrders> logger, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_logic = reportLogic;
reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
reportViewer.LocalReport.LoadReportDefinition(new FileStream("ReportOrdersByDate.rdlc", FileMode.Open));
Controls.Clear();
Controls.Add(reportViewer);
Controls.Add(panel);
}
private void buttonCreateReport_Click(object sender, EventArgs e)
{
try
{
var dataSource = _logic.GetDateOrders();
var source = new ReportDataSource("DataSetOrders", dataSource);
reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(source);
reportViewer.RefreshReport();
_logger.LogInformation("Загрузка списка заказов на весь период по датам");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCreateToPdf_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" };
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveDateOrdersToPdfFile(new ReportBindingModel
{
FileName = dialog.FileName
});
_logger.LogInformation("Сохранение списка заказов на весь период по датам");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

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

View File

@ -0,0 +1,107 @@
namespace LawFirmView
{
partial class FormReportShopDocuments
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.buttonSaveToExcel = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.Shop = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Document = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// buttonSaveToExcel
//
this.buttonSaveToExcel.Location = new System.Drawing.Point(12, 8);
this.buttonSaveToExcel.Name = "buttonSaveToExcel";
this.buttonSaveToExcel.Size = new System.Drawing.Size(176, 29);
this.buttonSaveToExcel.TabIndex = 0;
this.buttonSaveToExcel.Text = "Сохранить в Excel";
this.buttonSaveToExcel.UseVisualStyleBackColor = true;
this.buttonSaveToExcel.Click += new System.EventHandler(this.buttonSaveToExcel_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Shop,
this.Document,
this.Count});
this.dataGridView.Location = new System.Drawing.Point(12, 43);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(776, 395);
this.dataGridView.TabIndex = 1;
//
// Shop
//
this.Shop.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.Shop.HeaderText = "Магазин";
this.Shop.MinimumWidth = 6;
this.Shop.Name = "Shop";
//
// Document
//
this.Document.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.Document.HeaderText = "Документ";
this.Document.MinimumWidth = 6;
this.Document.Name = "Document";
//
// Count
//
this.Count.HeaderText = "Количество";
this.Count.MinimumWidth = 6;
this.Count.Name = "Count";
this.Count.Width = 125;
//
// FormReportShopDocuments
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.buttonSaveToExcel);
this.Name = "FormReportShopDocuments";
this.Text = "Документы в магазинах";
this.Load += new System.EventHandler(this.FormReportShopDocuments_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Button buttonSaveToExcel;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn Shop;
private DataGridViewTextBoxColumn Document;
private DataGridViewTextBoxColumn Count;
}
}

View File

@ -0,0 +1,85 @@
using LawFirmBusinessLogic.BusinessLogics;
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LawFirmView
{
public partial class FormReportShopDocuments : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportShopDocuments(ILogger<FormReportShopDocuments> logger, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_logic = reportLogic;
}
private void buttonSaveToExcel_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog
{
Filter = "xlsx|*.xlsx"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveShopDocumentsToExcelFile(new ReportBindingModel
{
FileName = dialog.FileName
});
_logger.LogInformation("Сохранение списка магазинов с изделиями в них");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка магазинов с изделиями в них");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void FormReportShopDocuments_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetShopDocuments();
if (dict != null)
{
dataGridView.Rows.Clear();
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" });
foreach (var listElem in elem.Documents)
{
dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 });
}
dataGridView.Rows.Add(new object[] { "Всего:", "", elem.Count });
dataGridView.Rows.Add(Array.Empty<object>());
}
}
_logger.LogInformation("Загрузка списка магазинов с изделиями в них");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка магазинов с изделиями в них");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,78 @@
<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>
<metadata name="Shop.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Document.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Shop.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Document.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

210
LawFirm/LawFirm/FormShop.Designer.cs generated Normal file
View File

@ -0,0 +1,210 @@
namespace LawFirmView
{
partial class FormShop
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBoxAddress = new System.Windows.Forms.TextBox();
this.textBoxName = new System.Windows.Forms.TextBox();
this.labelAddress = new System.Windows.Forms.Label();
this.labelName = new System.Windows.Forms.Label();
this.labelOpeningDate = new System.Windows.Forms.Label();
this.dateTimePicker = new System.Windows.Forms.DateTimePicker();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ColumnId = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnDocumentName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.labelMaxCount = new System.Windows.Forms.Label();
this.textBoxMaxCountDocs = new System.Windows.Forms.TextBox();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// textBoxAddress
//
this.textBoxAddress.Location = new System.Drawing.Point(100, 45);
this.textBoxAddress.Name = "textBoxAddress";
this.textBoxAddress.Size = new System.Drawing.Size(315, 27);
this.textBoxAddress.TabIndex = 7;
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(100, 12);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(315, 27);
this.textBoxName.TabIndex = 6;
//
// labelAddress
//
this.labelAddress.AutoSize = true;
this.labelAddress.Location = new System.Drawing.Point(14, 51);
this.labelAddress.Name = "labelAddress";
this.labelAddress.Size = new System.Drawing.Size(54, 20);
this.labelAddress.TabIndex = 5;
this.labelAddress.Text = "Адрес:";
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(14, 15);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(80, 20);
this.labelName.TabIndex = 4;
this.labelName.Text = "Название:";
//
// labelOpeningDate
//
this.labelOpeningDate.AutoSize = true;
this.labelOpeningDate.Location = new System.Drawing.Point(14, 86);
this.labelOpeningDate.Name = "labelOpeningDate";
this.labelOpeningDate.Size = new System.Drawing.Size(126, 20);
this.labelOpeningDate.TabIndex = 8;
this.labelOpeningDate.Text = "Время открытия:";
//
// dateTimePicker
//
this.dateTimePicker.Location = new System.Drawing.Point(165, 81);
this.dateTimePicker.Name = "dateTimePicker";
this.dateTimePicker.Size = new System.Drawing.Size(250, 27);
this.dateTimePicker.TabIndex = 9;
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnId,
this.ColumnDocumentName,
this.ColumnCount});
this.dataGridView.Location = new System.Drawing.Point(14, 173);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(401, 265);
this.dataGridView.TabIndex = 10;
//
// ColumnId
//
this.ColumnId.HeaderText = "ID";
this.ColumnId.MinimumWidth = 6;
this.ColumnId.Name = "ColumnId";
this.ColumnId.Visible = false;
this.ColumnId.Width = 125;
//
// ColumnDocumentName
//
this.ColumnDocumentName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ColumnDocumentName.HeaderText = "Документ";
this.ColumnDocumentName.MinimumWidth = 6;
this.ColumnDocumentName.Name = "ColumnDocumentName";
//
// ColumnCount
//
this.ColumnCount.HeaderText = "Количество";
this.ColumnCount.MinimumWidth = 6;
this.ColumnCount.Name = "ColumnCount";
this.ColumnCount.Width = 125;
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(228, 448);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(155, 29);
this.buttonCancel.TabIndex = 12;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(48, 448);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(155, 29);
this.buttonSave.TabIndex = 11;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// labelMaxCount
//
this.labelMaxCount.AutoSize = true;
this.labelMaxCount.Location = new System.Drawing.Point(18, 128);
this.labelMaxCount.Name = "labelMaxCount";
this.labelMaxCount.Size = new System.Drawing.Size(216, 20);
this.labelMaxCount.TabIndex = 13;
this.labelMaxCount.Text = "Макс. количество документов";
//
// textBoxMaxCountDocs
//
this.textBoxMaxCountDocs.Location = new System.Drawing.Point(240, 128);
this.textBoxMaxCountDocs.Name = "textBoxMaxCountDocs";
this.textBoxMaxCountDocs.Size = new System.Drawing.Size(175, 27);
this.textBoxMaxCountDocs.TabIndex = 14;
//
// FormShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(445, 489);
this.Controls.Add(this.textBoxMaxCountDocs);
this.Controls.Add(this.labelMaxCount);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.dateTimePicker);
this.Controls.Add(this.labelOpeningDate);
this.Controls.Add(this.textBoxAddress);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.labelAddress);
this.Controls.Add(this.labelName);
this.Name = "FormShop";
this.Text = "Магазин";
this.Load += new System.EventHandler(this.FormShop_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxAddress;
private TextBox textBoxName;
private Label labelAddress;
private Label labelName;
private Label labelOpeningDate;
private DateTimePicker dateTimePicker;
private DataGridView dataGridView;
private Button buttonCancel;
private Button buttonSave;
private DataGridViewTextBoxColumn ColumnId;
private DataGridViewTextBoxColumn ColumnDocumentName;
private DataGridViewTextBoxColumn ColumnCount;
private Label labelMaxCount;
private TextBox textBoxMaxCountDocs;
}
}

144
LawFirm/LawFirm/FormShop.cs Normal file
View File

@ -0,0 +1,144 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.SearchModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
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 FormShop : Form
{
private readonly IShopLogic _logic;
private readonly ILogger _logger;
private Dictionary<int, (IDocumentModel, int)> _shopDocuments;
private int? _id;
public int Id { set { _id = value; } }
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_shopDocuments = new();
}
private void FormShop_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка магазина");
try
{
var view = _logic.ReadElement(new ShopSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.Name;
textBoxAddress.Text = view.Adress;
_shopDocuments = view.ShopDocuments ?? new Dictionary<int, (IDocumentModel, int)>();
textBoxMaxCountDocs.Text = view.MaxCountDocuments.ToString();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка документов магазина");
try
{
if (_shopDocuments != null)
{
dataGridView.Rows.Clear();
foreach (var pc in _shopDocuments)
{
dataGridView.Rows.Add(new object[]
{
pc.Key,
pc.Value.Item1.DocumentName,
pc.Value.Item2
}
);
}
}
}
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(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxAddress.Text))
{
MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxMaxCountDocs.Text))
{
MessageBox.Show("Заполните макс. количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение магазина");
try
{
var model = new ShopBindingModel
{
Id = _id ?? 0,
Name = textBoxName.Text,
Adress = textBoxAddress.Text,
OpeningDate = dateTimePicker.Value.Date,
MaxCountDocuments = Convert.ToInt32(textBoxMaxCountDocs.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,69 @@
<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>
<metadata name="ColumnId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnDocumentName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

119
LawFirm/LawFirm/FormShopSell.Designer.cs generated Normal file
View File

@ -0,0 +1,119 @@
namespace LawFirmView
{
partial class FormShopSell
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.labelCount = new System.Windows.Forms.Label();
this.labelDocument = new System.Windows.Forms.Label();
this.comboBoxDocument = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonSell = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(23, 76);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(93, 20);
this.labelCount.TabIndex = 1;
this.labelCount.Text = "Количество:";
//
// labelDocument
//
this.labelDocument.AutoSize = true;
this.labelDocument.Location = new System.Drawing.Point(23, 24);
this.labelDocument.Name = "labelDocument";
this.labelDocument.Size = new System.Drawing.Size(79, 20);
this.labelDocument.TabIndex = 2;
this.labelDocument.Text = "Документ:";
//
// comboBoxDocument
//
this.comboBoxDocument.FormattingEnabled = true;
this.comboBoxDocument.Location = new System.Drawing.Point(124, 24);
this.comboBoxDocument.Name = "comboBoxDocument";
this.comboBoxDocument.Size = new System.Drawing.Size(278, 28);
this.comboBoxDocument.TabIndex = 4;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(124, 73);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(158, 27);
this.textBoxCount.TabIndex = 5;
//
// buttonSell
//
this.buttonSell.Location = new System.Drawing.Point(188, 142);
this.buttonSell.Name = "buttonSell";
this.buttonSell.Size = new System.Drawing.Size(94, 29);
this.buttonSell.TabIndex = 6;
this.buttonSell.Text = "Продажа";
this.buttonSell.UseVisualStyleBackColor = true;
this.buttonSell.Click += new System.EventHandler(this.buttonSell_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(308, 142);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 7;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormShopSell
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(459, 198);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSell);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxDocument);
this.Controls.Add(this.labelDocument);
this.Controls.Add(this.labelCount);
this.Name = "FormShopSell";
this.Text = "Продажа из магазина";
this.Load += new System.EventHandler(this.FormShopSell_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelCount;
private Label labelDocument;
private ComboBox comboBoxDocument;
private TextBox textBoxCount;
private Button buttonSell;
private Button buttonCancel;
}
}

View File

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

View File

@ -0,0 +1,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>

144
LawFirm/LawFirm/FormShopSupply.Designer.cs generated Normal file
View File

@ -0,0 +1,144 @@
namespace LawFirmView
{
partial class FormShopSupply
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.labelShop = new System.Windows.Forms.Label();
this.labelDocument = new System.Windows.Forms.Label();
this.labelDocumentCount = new System.Windows.Forms.Label();
this.comboBoxShop = new System.Windows.Forms.ComboBox();
this.comboBoxDocument = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelShop
//
this.labelShop.AutoSize = true;
this.labelShop.Location = new System.Drawing.Point(26, 19);
this.labelShop.Name = "labelShop";
this.labelShop.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.labelShop.Size = new System.Drawing.Size(72, 20);
this.labelShop.TabIndex = 0;
this.labelShop.Text = "Магазин:";
//
// labelDocument
//
this.labelDocument.AutoSize = true;
this.labelDocument.Location = new System.Drawing.Point(26, 72);
this.labelDocument.Name = "labelDocument";
this.labelDocument.Size = new System.Drawing.Size(79, 20);
this.labelDocument.TabIndex = 1;
this.labelDocument.Text = "Документ:";
//
// labelDocumentCount
//
this.labelDocumentCount.AutoSize = true;
this.labelDocumentCount.Location = new System.Drawing.Point(26, 122);
this.labelDocumentCount.Name = "labelDocumentCount";
this.labelDocumentCount.Size = new System.Drawing.Size(93, 20);
this.labelDocumentCount.TabIndex = 2;
this.labelDocumentCount.Text = "Количество:";
//
// comboBoxShop
//
this.comboBoxShop.FormattingEnabled = true;
this.comboBoxShop.Location = new System.Drawing.Point(148, 19);
this.comboBoxShop.Name = "comboBoxShop";
this.comboBoxShop.Size = new System.Drawing.Size(251, 28);
this.comboBoxShop.TabIndex = 3;
//
// comboBoxDocument
//
this.comboBoxDocument.FormattingEnabled = true;
this.comboBoxDocument.Location = new System.Drawing.Point(148, 69);
this.comboBoxDocument.Name = "comboBoxDocument";
this.comboBoxDocument.Size = new System.Drawing.Size(251, 28);
this.comboBoxDocument.TabIndex = 4;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(148, 122);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(125, 27);
this.textBoxCount.TabIndex = 5;
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(305, 183);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 9;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(205, 183);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 8;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// FormShopSupply
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(436, 243);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxDocument);
this.Controls.Add(this.comboBoxShop);
this.Controls.Add(this.labelDocumentCount);
this.Controls.Add(this.labelDocument);
this.Controls.Add(this.labelShop);
this.Name = "FormShopSupply";
this.Text = "Пополнение магазина";
this.Load += new System.EventHandler(this.FormShopSupply_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelShop;
private Label labelDocument;
private Label labelDocumentCount;
private ComboBox comboBoxShop;
private ComboBox comboBoxDocument;
private TextBox textBoxCount;
private Button buttonCancel;
private Button buttonSave;
}
}

View File

@ -0,0 +1,125 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.SearchModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LawFirmView
{
public partial class FormShopSupply : Form
{
private readonly ILogger _logger;
private readonly IDocumentLogic _logicD;
private readonly IShopLogic _logicS;
public FormShopSupply(ILogger<FormShopSupply> logger, IDocumentLogic logicD, IShopLogic logicS)
{
InitializeComponent();
_logger = logger;
_logicD = logicD;
_logicS = logicS;
}
private void FormShopSupply_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка документов для пополнения");
try
{
var list = _logicD.ReadList(null);
if (list != null)
{
comboBoxDocument.DisplayMember = "DocumentName";
comboBoxDocument.ValueMember = "Id";
comboBoxDocument.DataSource = list;
comboBoxDocument.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка документов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_logger.LogInformation("Загрузка магазинов для пополнения");
try
{
var list = _logicS.ReadList(null);
if (list != null)
{
comboBoxShop.DisplayMember = "Name";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = list;
comboBoxShop.SelectedItem = null;
}
}
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(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxDocument.SelectedValue == null)
{
MessageBox.Show("Выберите документ", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxShop.SelectedValue== null)
{
MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание поставки");
try
{
var operationResult = _logicS.SupplyDocuments(
new ShopSearchModel
{
Id = Convert.ToInt32(comboBoxShop.SelectedValue),
Name = comboBoxShop.Text
},
new DocumentBindingModel
{
Id = Convert.ToInt32(comboBoxDocument.SelectedValue),
DocumentName = comboBoxDocument.Text
},
Convert.ToInt32(textBoxCount.Text)
);
if (!operationResult)
{
throw new Exception("Ошибка при создании поставки. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания поставки");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,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>

115
LawFirm/LawFirm/FormShops.Designer.cs generated Normal file
View File

@ -0,0 +1,115 @@
namespace LawFirmView
{
partial class FormShops
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonEdit = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(12, 12);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(561, 426);
this.dataGridView.TabIndex = 0;
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(627, 409);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(152, 29);
this.buttonUpdate.TabIndex = 9;
this.buttonUpdate.Text = "Обновить";
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.buttonUpdate_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(627, 82);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(152, 29);
this.buttonDelete.TabIndex = 8;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.buttonDelete_Click);
//
// buttonEdit
//
this.buttonEdit.Location = new System.Drawing.Point(627, 47);
this.buttonEdit.Name = "buttonEdit";
this.buttonEdit.Size = new System.Drawing.Size(152, 29);
this.buttonEdit.TabIndex = 7;
this.buttonEdit.Text = "Изменить";
this.buttonEdit.UseVisualStyleBackColor = true;
this.buttonEdit.Click += new System.EventHandler(this.buttonEdit_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(627, 12);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(152, 29);
this.buttonAdd.TabIndex = 6;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// FormShops
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.buttonUpdate);
this.Controls.Add(this.buttonDelete);
this.Controls.Add(this.buttonEdit);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.dataGridView);
this.Name = "FormShops";
this.Text = "Магазины";
this.Load += new System.EventHandler(this.FormShops_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonEdit;
private Button buttonAdd;
}
}

View File

@ -0,0 +1,124 @@
using LawFirm;
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LawFirmView
{
public partial class FormShops : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public FormShops(ILogger<FormDocuments> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormShops_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["Name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ShopDocuments"].Visible = false;
}
_logger.LogInformation("Загрузка магазинов");
}
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 buttonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void buttonEdit_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void buttonDelete_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 ShopBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
}

View File

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

View File

@ -74,6 +74,7 @@ namespace LawFirm
DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
DependencyManager.Instance.RegisterType<IShopLogic, ShopLogic>();
DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
@ -94,8 +95,15 @@ namespace LawFirm
DependencyManager.Instance.RegisterType<FormImplementers>();
DependencyManager.Instance.RegisterType<FormImplementer>();
DependencyManager.Instance.RegisterType<FormMails>();
}
DependencyManager.Instance.RegisterType<FormMail>();
DependencyManager.Instance.RegisterType<FormReportShopDocuments>();
DependencyManager.Instance.RegisterType<FormReportDateOrders>();
DependencyManager.Instance.RegisterType<FormShop>();
DependencyManager.Instance.RegisterType<FormShops>();
DependencyManager.Instance.RegisterType<FormShopSupply>();
DependencyManager.Instance.RegisterType<FormShopSell>();
}
}
}

View File

@ -0,0 +1,424 @@
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
<AutoRefresh>0</AutoRefresh>
<DataSources>
<DataSource Name="LawFirmContractsViewModels">
<ConnectionProperties>
<DataProvider>System.Data.DataSet</DataProvider>
<ConnectString>/* Local Connection */</ConnectString>
</ConnectionProperties>
<rd:DataSourceID>10791c83-cee8-4a38-bbd0-245fc17cefb3</rd:DataSourceID>
</DataSource>
</DataSources>
<DataSets>
<DataSet Name="DataSetOrders">
<Query>
<DataSourceName>LawFirmContractsViewModels</DataSourceName>
<CommandText>/* Local Query */</CommandText>
</Query>
<Fields>
<Field Name="DateCreate">
<DataField>DateCreate</DataField>
<rd:TypeName>System.DateTime</rd:TypeName>
</Field>
<Field Name="CountOrders">
<DataField>CountOrders</DataField>
<rd:TypeName>System.Decimal</rd:TypeName>
</Field>
<Field Name="SumOrders">
<DataField>SumOrders</DataField>
<rd:TypeName>System.Double</rd:TypeName>
</Field>
</Fields>
<rd:DataSetInfo>
<rd:DataSetName>LawFirmContracts.ViewModels</rd:DataSetName>
<rd:TableName>ReportDateOrdersViewModel</rd:TableName>
<rd:ObjectDataSourceType>LawFirmContracts.ViewModels.ReportDateOrdersViewModel, LawFirmContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</rd:ObjectDataSourceType>
</rd:DataSetInfo>
</DataSet>
</DataSets>
<ReportSections>
<ReportSection>
<Body>
<ReportItems>
<Textbox Name="TextboxTitle">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Заказы</Value>
<Style>
<FontSize>16pt</FontSize>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Height>1cm</Height>
<Width>21cm</Width>
<Style>
<Border>
<Style>None</Style>
</Border>
<VerticalAlign>Middle</VerticalAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Tablix Name="Tablix1">
<TablixBody>
<TablixColumns>
<TablixColumn>
<Width>3cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3cm</Width>
</TablixColumn>
<TablixColumn>
<Width>7cm</Width>
</TablixColumn>
</TablixColumns>
<TablixRows>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="Textbox1">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Дата</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox1</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Textbox3">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Количество</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox3</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Textbox2">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Сумма</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox2</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="DateCreate">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!DateCreate.Value</Value>
<Style>
<Format>d</Format>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>DateCreate</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="CountOrders">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!CountOrders.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>CountOrders</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="SumOrders">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!SumOrders.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>SumOrders</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
</TablixRows>
</TablixBody>
<TablixColumnHierarchy>
<TablixMembers>
<TablixMember />
<TablixMember />
<TablixMember />
</TablixMembers>
</TablixColumnHierarchy>
<TablixRowHierarchy>
<TablixMembers>
<TablixMember>
<KeepWithGroup>After</KeepWithGroup>
</TablixMember>
<TablixMember>
<Group Name="Подробности" />
</TablixMember>
</TablixMembers>
</TablixRowHierarchy>
<DataSetName>DataSetOrders</DataSetName>
<Top>2.48391cm</Top>
<Left>0.55245cm</Left>
<Height>1.2cm</Height>
<Width>13cm</Width>
<ZIndex>1</ZIndex>
<Style>
<Border>
<Style>Double</Style>
</Border>
</Style>
</Tablix>
<Textbox Name="TextboxTotalSum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Всего:</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>4cm</Top>
<Left>8.55245cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</Width>
<ZIndex>2</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Textbox Name="SumTotal">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Sum(Fields!SumOrders.Value, "DataSetOrders")</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>4cm</Top>
<Left>11.05245cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</Width>
<ZIndex>3</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</ReportItems>
<Height>5.72875cm</Height>
<Style />
</Body>
<Width>21cm</Width>
<Page>
<PageHeight>29.7cm</PageHeight>
<PageWidth>21cm</PageWidth>
<LeftMargin>2cm</LeftMargin>
<RightMargin>2cm</RightMargin>
<TopMargin>2cm</TopMargin>
<BottomMargin>2cm</BottomMargin>
<ColumnSpacing>0.13cm</ColumnSpacing>
<Style />
</Page>
</ReportSection>
</ReportSections>
<ReportParameters>
<ReportParameter Name="ReportParameterPeriod">
<DataType>String</DataType>
<Nullable>true</Nullable>
<Prompt>ReportParameter1</Prompt>
</ReportParameter>
</ReportParameters>
<ReportParametersLayout>
<GridLayoutDefinition>
<NumberOfColumns>4</NumberOfColumns>
<NumberOfRows>2</NumberOfRows>
<CellDefinitions>
<CellDefinition>
<ColumnIndex>0</ColumnIndex>
<RowIndex>0</RowIndex>
<ParameterName>ReportParameterPeriod</ParameterName>
</CellDefinition>
</CellDefinitions>
</GridLayoutDefinition>
</ReportParametersLayout>
<rd:ReportUnitType>Cm</rd:ReportUnitType>
<rd:ReportID>2de0031a-4d17-449d-922d-d9fc54572312</rd:ReportID>
</Report>

View File

@ -32,7 +32,18 @@ namespace LawFirmBusinessLogic.BusinessLogics
return true;
}
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
public MessageInfoViewModel? ReadElement(MessageInfoSearchModel model)
{
var message = _messageInfoStorage.GetElement(model);
if (message == null)
{
_logger.LogWarning("Read message operation failed");
return null;
}
return message;
}
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
{
_logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId);
var list = (model == null) ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model);
@ -44,5 +55,15 @@ namespace LawFirmBusinessLogic.BusinessLogics
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
}
public bool Update(MessageInfoBindingModel model)
{
if (_messageInfoStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
}
}

View File

@ -5,6 +5,7 @@ using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Enums;
using LawFirmDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@ -18,13 +19,20 @@ namespace LawFirmBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly IShopLogic _shopLogic;
private readonly IDocumentStorage _documentStorage;
private readonly AbstractMailWorker _mailWorker;
private readonly IClientLogic _clientLogic;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic)
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopLogic shopLogic, IDocumentStorage documentStorage, IShopStorage shopStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic)
{
_logger = logger;
_orderStorage = orderStorage;
_shopLogic = shopLogic;
_documentStorage = documentStorage;
_shopStorage = shopStorage;
_mailWorker = mailWorker;
_clientLogic = clientLogic;
}
@ -79,11 +87,29 @@ namespace LawFirmBusinessLogic.BusinessLogics
}
CheckModel(model, false);
if (model.Status + 1 != newStatus)
if (model.Status + 1 != newStatus && model.Status!=OrderStatus.Ожидание)
{
_logger.LogWarning("Status update to " + newStatus.ToString() +" operation failed. Order status incorrect.");
return false;
}
if (newStatus == OrderStatus.Готов)
{
var document = _documentStorage.GetElement(new DocumentSearchModel() { Id = model.DocumentId});
if (document == null)
{
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Document not found.");
return false;
}
if (CheckThenSupplyMany(document, model.Count) == false)
{
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Shop supply error.");
model.Status = OrderStatus.Ожидание;
_orderStorage.Update(model);
return false;
}
}
model.Status = newStatus;
if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now;
var result = _orderStorage.Update(model);
@ -97,6 +123,67 @@ namespace LawFirmBusinessLogic.BusinessLogics
return true;
}
public bool CheckThenSupplyMany(IDocumentModel document, int count)
{
if (count <= 0)
{
_logger.LogWarning("Check then supply operation error. Document count < 0.");
return false;
}
int freeSpace = 0;
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace += shop.MaxCountDocuments;
foreach (var doc in shop.ShopDocuments)
{
freeSpace -= doc.Value.Item2;
}
}
if (freeSpace - count < 0)
{
_logger.LogWarning("Check then supply operation error. There's no place for new docs in shops.");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace = shop.MaxCountDocuments;
foreach (var doc in shop.ShopDocuments)
{
freeSpace -= doc.Value.Item2;
}
if (freeSpace == 0)
{
continue;
}
if (freeSpace - count >= 0)
{
if (_shopLogic.SupplyDocuments(new() { Id = shop.Id }, document, count)) count = 0;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (freeSpace - count < 0)
{
if (_shopLogic.SupplyDocuments(new() { Id = shop.Id }, document, freeSpace)) count -= freeSpace;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выполняется);

View File

@ -18,14 +18,16 @@ namespace LawFirmBusinessLogic.BusinessLogics
private readonly IBlankStorage _blankStorage;
private readonly IDocumentStorage _documentStorage;
private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IDocumentStorage documentStorage, IBlankStorage blankStorage, IOrderStorage orderStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
public ReportLogic(IDocumentStorage documentStorage, IBlankStorage blankStorage, IOrderStorage orderStorage, IShopStorage shopStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
{
_documentStorage = documentStorage;
_blankStorage = blankStorage;
_orderStorage = orderStorage;
_shopStorage = shopStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
@ -104,5 +106,64 @@ namespace LawFirmBusinessLogic.BusinessLogics
});
}
public void SaveShopsToWordFile(ReportBindingModel model)
{
_saveToWord.CreateTableDoc(new WordInfo
{
FileName = model.FileName,
Title = "Список магазинов",
Shops = _shopStorage.GetFullList()
});
}
public void SaveShopDocumentsToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateShopReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Загруженность магазинов",
ShopDocuments = GetShopDocuments()
});
}
public List<ReportShopDocumentsViewModel> GetShopDocuments()
{
var shops = _shopStorage.GetFullList();
var list = new List<ReportShopDocumentsViewModel>();
foreach (var shop in shops)
{
var record = new ReportShopDocumentsViewModel
{
ShopName = shop.Name,
Documents = new List<Tuple<string, int>>(),
Count = 0
};
foreach (var docCount in shop.ShopDocuments.Values)
{
record.Documents.Add(new Tuple<string, int>(docCount.Item1.DocumentName, docCount.Item2));
record.Count += docCount.Item2;
}
list.Add(record);
}
return list;
}
public List<ReportDateOrdersViewModel> GetDateOrders()
{
return _orderStorage.GetFullList().GroupBy(x => x.DateCreate.Date).Select(x => new ReportDateOrdersViewModel
{
DateCreate = x.Key,
CountOrders = x.Count(),
SumOrders = x.Sum(y => y.Sum)
}).ToList();
}
public void SaveDateOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateReportDateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Заказы по датам",
DateOrders = GetDateOrders()
});
}
}
}

View File

@ -0,0 +1,189 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace LawFirmBusinessLogic.BusinessLogics
{
public class ShopLogic : IShopLogic
{
private readonly ILogger _logger;
private readonly IShopStorage _shopStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage)
{
_logger = logger;
_shopStorage = shopStorage;
}
public ShopViewModel? ReadElement(ShopSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Shop Name:{0}.ID:{1}", model.Name, model.Id);
var element = _shopStorage.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<ShopViewModel>? ReadList(ShopSearchModel? model)
{
_logger.LogInformation("ReadList. Shop Name:{0}.ID:{1} ", model?.Name, model?.Id);
var list = (model == null) ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool SupplyDocuments(ShopSearchModel model, IDocumentModel document, int count)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
if (count <= 0)
{
throw new ArgumentNullException("Count of documents in supply myst be more than 0", nameof(count));
}
var shopElement = _shopStorage.GetElement(model);
if (shopElement == null)
{
_logger.LogWarning("Required shop element not found in storage");
return false;
}
_logger.LogInformation("Shop element found. ID: {0}, Name: {1}", shopElement.Id, shopElement.Name);
var countDocs = 0;
foreach (var doc in shopElement.ShopDocuments)
{
countDocs += doc.Value.Item2;
}
if (shopElement.MaxCountDocuments - countDocs >= count)
{
if (shopElement.ShopDocuments.TryGetValue(document.Id, out var sameDocument))
{
shopElement.ShopDocuments[document.Id] = (document, sameDocument.Item2 + count);
_logger.LogInformation("Same document found by supply. Added {0} of {1} in {2} shop", count, document.DocumentName, shopElement.Name);
}
else
{
shopElement.ShopDocuments[document.Id] = (document, count);
_logger.LogInformation("New document added by supply. Added {0} of {1} in {2} shop", count, document.DocumentName, shopElement.Name);
}
_shopStorage.Update(new()
{
Id = shopElement.Id,
Name = shopElement.Name,
Adress = shopElement.Adress,
OpeningDate = shopElement.OpeningDate,
ShopDocuments = shopElement.ShopDocuments,
MaxCountDocuments = shopElement.MaxCountDocuments
});
}
else
{
_logger.LogWarning("Required shop is overflowed");
return false;
}
return true;
}
public bool SellDocument(IDocumentModel document, int count)
{;
return _shopStorage.SellDocument(document, count);
}
public bool Create(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ShopBindingModel model)
{
CheckModel(model, false);
if (_shopStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ShopBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Нет названия магазина!", nameof(model.Name));
}
if (model.MaxCountDocuments < 0)
{
throw new InvalidOperationException("Магазин с отрицательным количеством максимального количества документов!");
}
_logger.LogInformation("Shop. Name: {0}, Adress: {1}, ID: {2}", model.Name, model.Adress, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
Name = model.Name
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
}
}

View File

@ -35,7 +35,12 @@ namespace LawFirmBusinessLogic.BusinessLogics
_logger.LogWarning("DoWork. Implementers is null");
return;
}
var orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Принят });
var orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Принят });
if (orders != null) {
orders.AddRange(_orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Выполняется }) ?? new());
orders.AddRange(_orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Ожидание }) ?? new());
}
if (orders == null || orders.Count == 0)
{
_logger.LogWarning("DoWork. Orders is null or empty");
@ -54,6 +59,9 @@ namespace LawFirmBusinessLogic.BusinessLogics
{
return;
}
await RunWaitingOrder(implementer);
await RunOrderInWork(implementer);
await Task.Run(() =>
@ -100,44 +108,82 @@ namespace LawFirmBusinessLogic.BusinessLogics
private async Task RunOrderInWork(ImplementerViewModel implementer)
{
if (_orderLogic == null || implementer == null)
{
return;
}
try
{
if (_orderLogic == null || implementer == null)
{
return;
}
try
{
// Выбираем из всех заказов тот, который выполняется данным исполнителем
var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Выполняется
}));
if (runOrder == null)
{
return;
}
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id);
// доделываем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) * runOrder.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id);
_orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = runOrder.Id,
ImplementerId = implementer.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;
}
}
private async Task RunWaitingOrder(ImplementerViewModel implementer)
{
if (_orderLogic == null || implementer == null)
{
return;
}
try
{
var order = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Ожидание
}));
if (order == 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);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id);
_orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = runOrder.Id
Id = order.Id,
ImplementerId = implementer.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

@ -27,6 +27,7 @@ namespace LawFirmBusinessLogic.OfficePackage
CellToName = "C1"
});
uint rowIndex = 2;
foreach (var pc in info.DocumentBlanks)
{
InsertCellInWorksheet(new ExcelCellParameters
@ -73,6 +74,69 @@ namespace LawFirmBusinessLogic.OfficePackage
}
SaveExcel(info);
}
public void CreateShopReport(ExcelInfo info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint rowIndex = 2;
foreach (var pc in info.ShopDocuments)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = pc.ShopName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var (DocumentName, Count) in pc.Documents)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = DocumentName,
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = Count.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
rowIndex++;
}
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Итого",
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = pc.Count.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
}
SaveExcel(info);
}
/// Создание excel-файла
protected abstract void CreateExcel(ExcelInfo info);
/// Добавляем новую ячейку в лист

View File

@ -47,6 +47,39 @@ namespace LawFirmBusinessLogic.OfficePackage
});
SavePdf(info);
}
public void CreateReportDateDoc(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph
{
Text = info.Title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "3cm", "3cm", "7cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Дата", "Количество", "Сумма" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.DateOrders)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { order.DateCreate.ToShortDateString(), order.CountOrders.ToString(), order.SumOrders.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph
{
Text = $"Итого: {info.DateOrders.Sum(x => x.SumOrders)}\t",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
SavePdf(info);
}
/// Создание pdf-файла
protected abstract void CreatePdf(PdfInfo info);
/// Создание параграфа с текстом

View File

@ -39,11 +39,37 @@ namespace LawFirmBusinessLogic.OfficePackage
}
SaveWord(info);
}
public void CreateTableDoc(WordInfo wordInfo)
{
CreateWord(wordInfo);
var list = new List<string>();
foreach (var shop in wordInfo.Shops)
{
list.Add(shop.Name);
list.Add(shop.Adress);
list.Add(shop.OpeningDate.ToString());
}
var wordTable = new WordTable
{
Headers = new List<string> {
"Название",
"Адрес",
"Дата открытия"},
Texts = list
};
CreateTable(wordTable);
SaveWord(wordInfo);
}
/// Создание doc-файла
protected abstract void CreateWord(WordInfo info);
/// Создание абзаца с текстом
protected abstract void CreateParagraph(WordParagraph paragraph);
/// Сохранение файла
protected abstract void SaveWord(WordInfo info);
protected abstract void CreateTable(WordTable info);
}
}

View File

@ -12,5 +12,6 @@ namespace LawFirmBusinessLogic.OfficePackage.HelperModels
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportDocumentBlankViewModel> DocumentBlanks { get; set; } = new();
public List<ReportShopDocumentsViewModel> ShopDocuments { get; set; } = new();
}
}

View File

@ -14,5 +14,6 @@ namespace LawFirmBusinessLogic.OfficePackage.HelperModels
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportOrdersViewModel> Orders { get; set; } = new();
public List<ReportDateOrdersViewModel> DateOrders { get; set; } = new();
}
}

View File

@ -12,5 +12,6 @@ namespace LawFirmBusinessLogic.OfficePackage.HelperModels
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<DocumentViewModel> Documents { get; set; } = new();
public List<ShopViewModel> Shops { get; set; } = new();
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmBusinessLogic.OfficePackage.HelperModels
{
public class WordTable
{
public List<string> Headers { get; set; } = new();
public List<string> Texts { get; set; } = new();
}
}

View File

@ -112,5 +112,86 @@ namespace LawFirmBusinessLogic.OfficePackage.Implements
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Close();
}
protected override void CreateTable(WordTable table)
{
if (_docBody == null || table == null)
{
return;
}
Table tab = new Table();
TableProperties props = new TableProperties(
new TableBorders(
new TopBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new BottomBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new LeftBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new RightBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideHorizontalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideVerticalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
}
)
);
tab.AppendChild<TableProperties>(props);
TableGrid tableGrid = new TableGrid();
for (int i = 0; i < table.Headers.Count; i++)
{
tableGrid.AppendChild(new GridColumn());
}
tab.AppendChild(tableGrid);
TableRow tableRow = new TableRow();
foreach (var text in table.Headers)
{
tableRow.AppendChild(CreateTableCell(text));
}
tab.AppendChild(tableRow);
int height = table.Texts.Count / table.Headers.Count;
int width = table.Headers.Count;
for (int i = 0; i < height; i++)
{
tableRow = new TableRow();
for (int j = 0; j < width; j++)
{
var element = table.Texts[i * table.Headers.Count + j];
tableRow.AppendChild(CreateTableCell(element));
}
tab.AppendChild(tableRow);
}
_docBody.AppendChild(tab);
}
private TableCell CreateTableCell(string element)
{
var tableParagraph = new Paragraph();
var run = new Run();
run.AppendChild(new Text { Text = element });
tableParagraph.AppendChild(run);
var tableCell = new TableCell();
tableCell.AppendChild(tableParagraph);
return tableCell;
}
}
}

View File

@ -10,7 +10,8 @@ namespace LawFirmClientApp
{
private static readonly HttpClient _client = new();
public static ClientViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration configuration)
public static int CurrentPage { get; set; } = 0;
public static void Connect(IConfiguration configuration)
{
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();

View File

@ -4,6 +4,7 @@ using LawFirmContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Text;
namespace LawFirmClientApp.Controllers
{
@ -136,16 +137,54 @@ namespace LawFirmClientApp.Controllers
return count * (doc?.Price ?? 1);
}
[HttpGet]
public IActionResult Mails()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<MessageInfoViewModel>>($"api/client/getmessages?clientId={APIClient.Client.Id}"));
[HttpGet]
public IActionResult Mails()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
APIClient.CurrentPage = 0;
return View();
}
[HttpGet]
public Tuple<string?, string?, bool, bool>? SwitchPage(bool isNext)
{
if (isNext)
{
APIClient.CurrentPage++;
}
else
{
if (APIClient.CurrentPage == 1)
{
return null;
}
APIClient.CurrentPage--;
}
var messages = APIClient.GetRequest<List<MessageInfoViewModel>>($"api/client/getmessages?clientId={APIClient.Client!.Id}&pageNum={APIClient.CurrentPage}");
if (isNext && (messages == null || messages.Count == 0))
{
APIClient.CurrentPage--;
return Tuple.Create<string?, string?, bool, bool>(null, null, APIClient.CurrentPage != 1, false);
}
StringBuilder htmlTable = new();
foreach (var mail in messages)
{
htmlTable.Append("<tr>" +
$"<td>{mail.DateDelivery}</td>" +
$"<td>{mail.Subject}</td>" +
$"<td>{mail.Body}</td>" +
"<td>" + (mail.IsReaded ? "Прочитано" : "Непрочитано") + "</td>" +
$"<td>{mail.Reply}</td>" +
"</tr>");
}
return Tuple.Create<string?, string?, bool, bool>(htmlTable.ToString(), APIClient.CurrentPage.ToString(), APIClient.CurrentPage != 1, true);
}
}
}
}

View File

@ -1,54 +1,79 @@
@using LawFirmContracts.ViewModels
@model List<MessageInfoViewModel>
@{
ViewData["Title"] = "Mails";
@{
ViewData["Title"] = "Mails";
}
<div class="text-center">
<h1 class="display-4">Письма</h1>
<h1 class="display-4">Письма</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<table class="table">
<thead>
<tr>
<th>
Дата
</th>
<th>
Заголовок
</th>
<th>
Текст
</th>
<th>
Прочитано
</th>
<th>
Ответ
</th>
</tr>
</thead>
<tbody id="mails-table-body">
</tbody>
</table>
<ul class="pagination justify-content-center">
<li id="prev-page" class="page-item">
<a class="page-link" href="#" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
<span class="sr-only">Предыдущее</span>
</a>
</li>
<li class="page-item">
<a id="current-page" class="page-link"></a>
</li>
<li id="next-page" class="page-item">
<a class="page-link" href="#" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
<span class="sr-only">Следующее</span>
</a>
</li>
</ul>
</div>
<table class="table">
<thead>
<tr>
<th>
Дата письма
</th>
<th>
Заголовок
</th>
<th>
Текст
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DateDelivery)
</td>
<td>
@Html.DisplayFor(modelItem => item.Subject)
</td>
<td>
@Html.DisplayFor(modelItem => item.Body)
</td>
</tr>
}
</tbody>
</table>
}
</div>
<script>
function onClicked(isNext) {
$.ajax({
method: "GET",
url: "/Home/SwitchPage",
data: { isNext: isNext },
success: function (result) {
if (result != null) {
if (result.item1 != null && result.item2 != null) {
$("#mails-table-body").html(result.item1);
$("#current-page").text(result.item2);
}
if (result.item3)
$("#prev-page").removeClass("page-item disabled");
else
$("#prev-page").addClass("page-item disabled");
if (result.item4)
$("#next-page").removeClass("page-item disabled");
else
$("#next-page").addClass("page-item disabled");
}
}
});
}
onClicked(true);
$("#prev-page").on('click', () => onClicked(false));
$("#next-page").on('click', () => onClicked(true));
</script>

View File

@ -19,7 +19,11 @@ namespace LawFirmContracts.BindingModels
public string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public bool IsReaded { get; set; }
public string? Reply { get; set; }
public int Id => throw new NotImplementedException();
}

View File

@ -0,0 +1,24 @@
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.BindingModels
{
public class ShopBindingModel : IShopModel
{
public string Name { get; set; } = string.Empty;
public string Adress { get; set; } = string.Empty;
public DateTime OpeningDate { get; set; }
public Dictionary<int, (IDocumentModel, int)> ShopDocuments { get; set; } = new();
public int Id { get; set; }
public int MaxCountDocuments { get; set; }
}
}

View File

@ -13,5 +13,7 @@ namespace LawFirmContracts.BusinessLogicContracts
{
List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model);
bool Create(MessageInfoBindingModel model);
}
bool Update(MessageInfoBindingModel model);
MessageInfoViewModel? ReadElement(MessageInfoSearchModel model);
}
}

View File

@ -20,5 +20,11 @@ namespace LawFirmContracts.BusinessLogicContracts
void SaveProductComponentToExcelFile(ReportBindingModel model);
/// Сохранение заказов в файл-Pdf
void SaveOrdersToPdfFile(ReportBindingModel model);
// Сохранение магазинов в файл-Word
void SaveShopsToWordFile(ReportBindingModel model);
void SaveShopDocumentsToExcelFile(ReportBindingModel model);
List<ReportShopDocumentsViewModel> GetShopDocuments();
List<ReportDateOrdersViewModel> GetDateOrders();
void SaveDateOrdersToPdfFile(ReportBindingModel model);
}
}

View File

@ -0,0 +1,23 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.BusinessLogicContracts
{
public interface IShopLogic
{
ShopViewModel? ReadElement(ShopSearchModel model);
List<ShopViewModel>? ReadList(ShopSearchModel? model);
bool Create(ShopBindingModel model);
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool SupplyDocuments(ShopSearchModel model, IDocumentModel document, int count);
bool SellDocument(IDocumentModel document, int count);
}
}

View File

@ -10,5 +10,7 @@ namespace LawFirmContracts.SearchModels
{
public int? ClientId { get; set; }
public string? MessageId { get; set; }
public int? Page { get; set; }
public int? PageSize { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.SearchModels
{
public class ShopSearchModel
{
public int? Id { get; set; }
public string? Name { get; set; }
}
}

View File

@ -15,5 +15,6 @@ namespace LawFirmContracts.StorageContracts
List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model);
MessageInfoViewModel? GetElement(MessageInfoSearchModel model);
MessageInfoViewModel? Insert(MessageInfoBindingModel model);
}
MessageInfoViewModel? Update(MessageInfoBindingModel model);
}
}

View File

@ -0,0 +1,23 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.StorageContracts
{
public interface IShopStorage
{
ShopViewModel? GetElement(ShopSearchModel model);
List<ShopViewModel> GetFullList();
List<ShopViewModel> GetFilteredList(ShopSearchModel model);
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool SellDocument(IDocumentModel model, int count);
}
}

View File

@ -29,6 +29,12 @@ namespace LawFirmContracts.ViewModels
[Column("Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Body { get; set; } = string.Empty;
[Column("Прочитано", width: 30)]
public bool IsReaded { get; set; }
[Column("Ответ", width: 150)]
public string? Reply { get; set; }
[Column(visible: false)]
public int Id => throw new NotImplementedException();
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.ViewModels
{
public class ReportDateOrdersViewModel
{
public DateTime DateCreate { get; set; }
public int CountOrders { get; set; }
public double SumOrders { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.ViewModels
{
public class ReportShopDocumentsViewModel
{
public string ShopName { get; set; } = string.Empty;
public int Count { get; set; }
public List<Tuple<string, int>> Documents { get; set; } = new();
}
}

View File

@ -0,0 +1,28 @@
using LawFirmDataModels.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 ShopViewModel : IShopModel
{
[DisplayName("Название магазина")]
public string Name { get; set; } = string.Empty;
[DisplayName("Адрес")]
public string Adress { get; set; } = string.Empty;
[DisplayName("Дата открытия")]
public DateTime OpeningDate { get; set; }
public Dictionary<int, (IDocumentModel, int)> ShopDocuments { get; set; } = new();
public List<Tuple<string, int>>? DocumentCount { get; set; } = new();
public int Id { get; set; }
[DisplayName("Макс. документов в магазине")]
public int MaxCountDocuments { get; set; }
}
}

View File

@ -13,5 +13,6 @@ namespace LawFirmDataModels.Enums
Выполняется = 1,
Готов = 2,
Выдан = 3,
Ожидание = 4
}
}

View File

@ -14,5 +14,7 @@ namespace LawFirmDataModels.Models
DateTime DateDelivery { get; }
string Subject { get; }
string Body { get; }
}
public bool IsReaded { get; }
public string? Reply { get; }
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmDataModels.Models
{
public interface IShopModel : IId
{
String Name { get; }
String Adress { get; }
DateTime OpeningDate { get; }
Dictionary<int, (IDocumentModel, int)> ShopDocuments { get; }
int MaxCountDocuments { get; }
}
}

View File

@ -3,6 +3,7 @@ using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels;
using LawFirmDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
@ -27,10 +28,16 @@ namespace LawFirmDatabaseImplement.Implements
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
using var context = new LawFirmDatabase();
return context.Messages
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
var messages = context.Messages
.Where(x => (model.ClientId == null) || (x.ClientId == model.ClientId))
.Select(x => x.GetViewModel);
if (!(model.Page.HasValue && model.PageSize.HasValue))
{
return messages.ToList();
}
return messages.Skip((model.Page.Value - 1) * model.PageSize.Value).Take(model.PageSize.Value).ToList();
}
public List<MessageInfoViewModel> GetFullList()
@ -53,5 +60,17 @@ namespace LawFirmDatabaseImplement.Implements
context.SaveChanges();
return newMessage.GetViewModel;
}
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
using var context = new LawFirmDatabase();
var message = context.Messages.Include(x => x.Client).FirstOrDefault(x => x.MessageId.Equals(model.MessageId));
if (message != null)
{
message.Update(model);
context.SaveChanges();
}
return message?.GetViewModel;
}
}
}

View File

@ -17,6 +17,7 @@ namespace LawFirmDatabaseImplement.Implements
public OrderViewModel? GetElement(OrderSearchModel model)
{
using var context = new LawFirmDatabase();
return context.Orders
.Include(x => x.Document)
.Include(x => x.Client)
@ -44,16 +45,16 @@ namespace LawFirmDatabaseImplement.Implements
.Select(x => x.GetViewModel)
.ToList();
}
if (model.Status!= null)
if (model.Status != null)
{
return context.Orders
return context.Orders
.Include(x => x.Document)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => model.Status.Equals(x.Status))
.Select(x => x.GetViewModel)
.ToList();
}
.Include(x => x.Implementer)
.Where(x => model.Status.Equals(x.Status))
.Select(x => x.GetViewModel)
.ToList();
}
return context.Orders
.Include(x => x.Document)
.Include(x => x.Client)

View File

@ -0,0 +1,146 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels;
using LawFirmDatabaseImplement.Models;
using LawFirmDataModels.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmDatabaseImplement.Implements
{
public class ShopStorage : IShopStorage
{
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return new();
}
using var context = new LawFirmDatabase();
return context.Shops.Include(x => x.Documents).ThenInclude(x => x.Document).FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Name) && x.Name == model.Name) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new LawFirmDatabase();
return context.Shops.Include(x => x.Documents).ThenInclude(x => x.Document).Where(x => x.Name.Contains(model.Name)).ToList().Select(x => x.GetViewModel).ToList();
}
public List<ShopViewModel> GetFullList()
{
using var context = new LawFirmDatabase();
return context.Shops.Include(x => x.Documents).ThenInclude(x => x.Document).ToList().Select(x => x.GetViewModel).ToList();
}
public ShopViewModel? Insert(ShopBindingModel model)
{
using var context = new LawFirmDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var newShop = Shop.Create(context, model);
if (newShop == null)
{
return null;
}
if (context.Shops.Any(x => x.Name == newShop.Name))
{
throw new Exception("Название магазина уже занято");
}
context.Shops.Add(newShop);
context.SaveChanges();
transaction.Commit();
return newShop.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public ShopViewModel? Update(ShopBindingModel model)
{
using var context = new LawFirmDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var shop = context.Shops.Include(x => x.Documents).FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
context.SaveChanges();
if (model.ShopDocuments.Count > 0)
{
shop.UpdateDocuments(context, model);
}
transaction.Commit();
return shop.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public ShopViewModel? Delete(ShopBindingModel model)
{
using var context = new LawFirmDatabase();
var shop = context.Shops.Include(x => x.Documents).FirstOrDefault(x => x.Id == model.Id);
if (shop != null)
{
context.Shops.Remove(shop);
context.SaveChanges();
return shop.GetViewModel;
}
return null;
}
public bool SellDocument(IDocumentModel model, int count)
{
using var context = new LawFirmDatabase();
using var transaction = context.Database.BeginTransaction();
foreach (var shopDocs in context.ShopDocuments.Where(x => x.DocumentId == model.Id))
{
var min = Math.Min(count, shopDocs.Count);
shopDocs.Count -= min;
count -= min;
if (count <= 0)
{
break;
}
}
if (count == 0)
{
context.SaveChanges();
transaction.Commit();
}
else
{
transaction.Rollback();
}
if (count > 0)
{
return false;
}
return true;
}
}
}

View File

@ -23,6 +23,8 @@ namespace LawFirmDatabaseImplement
public virtual DbSet<Document> Documents { set; get; }
public virtual DbSet<DocumentBlank> DocumentBlanks { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopDocument> ShopDocuments { set; get; }
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
public virtual DbSet<MessageInfo> Messages { set; get; }

View File

@ -0,0 +1,248 @@
// <auto-generated />
using System;
using LawFirmDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace LawFirmDatabaseImplement.Migrations
{
[DbContext(typeof(LawFirmDatabase))]
[Migration("20230312152057_ShopsAdded")]
partial class ShopsAdded
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("BlankName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Blanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Document", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("DocumentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Documents");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("BlankId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("BlankId");
b.HasIndex("DocumentId");
b.ToTable("DocumentBlanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("DocumentId");
b.ToTable("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Adress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("MaxCountDocuments")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("OpeningDate")
.HasColumnType("datetime2");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.ShopDocument", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DocumentId");
b.HasIndex("ShopId");
b.ToTable("ShopDocuments");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Blank", "Blank")
.WithMany("DocumentBlanks")
.HasForeignKey("BlankId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany("Blanks")
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Blank");
b.Navigation("Document");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Order", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany("Orders")
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Document");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.ShopDocument", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany()
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Shop", "Shop")
.WithMany("Documents")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Document");
b.Navigation("Shop");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b =>
{
b.Navigation("DocumentBlanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Document", b =>
{
b.Navigation("Blanks");
b.Navigation("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Documents");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,78 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace LawFirmDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class ShopsAdded : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Shops",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
Adress = table.Column<string>(type: "nvarchar(max)", nullable: false),
OpeningDate = table.Column<DateTime>(type: "datetime2", nullable: false),
MaxCountDocuments = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Shops", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ShopDocuments",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
DocumentId = table.Column<int>(type: "int", nullable: false),
ShopId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ShopDocuments", x => x.Id);
table.ForeignKey(
name: "FK_ShopDocuments_Documents_DocumentId",
column: x => x.DocumentId,
principalTable: "Documents",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ShopDocuments_Shops_ShopId",
column: x => x.ShopId,
principalTable: "Shops",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ShopDocuments_DocumentId",
table: "ShopDocuments",
column: "DocumentId");
migrationBuilder.CreateIndex(
name: "IX_ShopDocuments_ShopId",
table: "ShopDocuments",
column: "ShopId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ShopDocuments");
migrationBuilder.DropTable(
name: "Shops");
}
}
}

View File

@ -1,4 +1,6 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
#nullable disable
@ -10,7 +12,7 @@ namespace LawFirmDatabaseImplement.Migrations
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
migrationBuilder.AddColumn<int>(
name: "ImplementerId",
table: "Orders",
type: "int",

View File

@ -0,0 +1,381 @@
// <auto-generated />
using System;
using LawFirmDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace LawFirmDatabaseImplement.Migrations
{
[DbContext(typeof(LawFirmDatabase))]
[Migration("20230422091213_MessageInfoUpdate")]
partial class MessageInfoUpdate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("BlankName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Blanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Document", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("DocumentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Documents");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("BlankId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("BlankId");
b.HasIndex("DocumentId");
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.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<bool>("IsReaded")
.HasColumnType("bit");
b.Property<string>("Reply")
.HasColumnType("nvarchar(max)");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("DocumentId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Adress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("MaxCountDocuments")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("OpeningDate")
.HasColumnType("datetime2");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.ShopDocument", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DocumentId");
b.HasIndex("ShopId");
b.ToTable("ShopDocuments");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Blank", "Blank")
.WithMany("DocumentBlanks")
.HasForeignKey("BlankId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany("Blanks")
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Blank");
b.Navigation("Document");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Client", "Client")
.WithMany("Messages")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Order", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany("Orders")
.HasForeignKey("DocumentId")
.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.ShopDocument", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany()
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Shop", "Shop")
.WithMany("Documents")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Document");
b.Navigation("Shop");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b =>
{
b.Navigation("DocumentBlanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Client", b =>
{
b.Navigation("Messages");
b.Navigation("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Document", b =>
{
b.Navigation("Blanks");
b.Navigation("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Documents");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,39 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace LawFirmDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class MessageInfoUpdate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsReaded",
table: "Messages",
type: "bit",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<string>(
name: "Reply",
table: "Messages",
type: "nvarchar(max)",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsReaded",
table: "Messages");
migrationBuilder.DropColumn(
name: "Reply",
table: "Messages");
}
}
}

View File

@ -155,6 +155,12 @@ namespace LawFirmDatabaseImplement.Migrations
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<bool>("IsReaded")
.HasColumnType("bit");
b.Property<string>("Reply")
.HasColumnType("nvarchar(max)");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
@ -213,6 +219,59 @@ namespace LawFirmDatabaseImplement.Migrations
b.ToTable("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Adress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("MaxCountDocuments")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("OpeningDate")
.HasColumnType("datetime2");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.ShopDocument", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DocumentId");
b.HasIndex("ShopId");
b.ToTable("ShopDocuments");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Blank", "Blank")
@ -266,6 +325,25 @@ namespace LawFirmDatabaseImplement.Migrations
b.Navigation("Implementer");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.ShopDocument", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany()
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Shop", "Shop")
.WithMany("Documents")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Document");
b.Navigation("Shop");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b =>
{
b.Navigation("DocumentBlanks");
@ -289,6 +367,11 @@ namespace LawFirmDatabaseImplement.Migrations
{
b.Navigation("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Documents");
});
#pragma warning restore 612, 618
}
}

View File

@ -29,8 +29,10 @@ namespace LawFirmDatabaseImplement.Models
public string Body { get; private set; } = string.Empty;
public virtual Client? Client { get; private set; }
public bool IsReaded { get; private set; }
public string? Reply { get; private set; }
public static MessageInfo? Create(MessageInfoBindingModel model)
public static MessageInfo? Create(MessageInfoBindingModel model)
{
if (model == null)
{
@ -44,10 +46,22 @@ namespace LawFirmDatabaseImplement.Models
MessageId = model.MessageId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
};
IsReaded = model.IsReaded,
Reply = model.Reply
};
}
public MessageInfoViewModel GetViewModel => new()
public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
Reply = model.Reply;
IsReaded = model.IsReaded;
}
public MessageInfoViewModel GetViewModel => new()
{
Body = Body,
Subject = Subject,
@ -55,7 +69,9 @@ namespace LawFirmDatabaseImplement.Models
MessageId = MessageId,
SenderName = SenderName,
DateDelivery = DateDelivery,
};
Reply = Reply,
IsReaded = IsReaded,
};
public int Id => throw new NotImplementedException();
}

View File

@ -0,0 +1,113 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmDatabaseImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
[Required]
public string Adress { get; set; } = string.Empty;
[Required]
public DateTime OpeningDate { get; set; }
[ForeignKey("ShopId")]
public List<ShopDocument> Documents { get; set; } = new();
private Dictionary<int, (IDocumentModel, int)>? _shopDocuments = null;
[NotMapped]
public Dictionary<int, (IDocumentModel, int)> ShopDocuments
{
get
{
if (_shopDocuments == null)
{
_shopDocuments = Documents.ToDictionary(recPC => recPC.DocumentId, recPC => (recPC.Document as IDocumentModel, recPC.Count));
}
return _shopDocuments;
}
}
[Required]
public int MaxCountDocuments { get; set; }
public static Shop Create(LawFirmDatabase context, ShopBindingModel model)
{
return new Shop()
{
Id = model.Id,
Name = model.Name,
Adress = model.Adress,
OpeningDate = model.OpeningDate,
Documents = model.ShopDocuments.Select(x => new ShopDocument
{
Document = context.Documents.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList(),
MaxCountDocuments = model.MaxCountDocuments
};
}
public void Update(ShopBindingModel model)
{
Name = model.Name;
Adress = model.Adress;
OpeningDate = model.OpeningDate;
MaxCountDocuments = model.MaxCountDocuments;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Adress = Adress,
OpeningDate = OpeningDate,
ShopDocuments = ShopDocuments,
MaxCountDocuments = MaxCountDocuments
};
public void UpdateDocuments(LawFirmDatabase context, ShopBindingModel model)
{
var ShopDocuments = context.ShopDocuments.Where(rec => rec.ShopId == model.Id).ToList();
if (ShopDocuments != null && ShopDocuments.Count > 0)
{
// удалили те, которых нет в модели
context.ShopDocuments.RemoveRange(ShopDocuments.Where(rec => !model.ShopDocuments.ContainsKey(rec.DocumentId)));
context.SaveChanges();
ShopDocuments = context.ShopDocuments.Where(rec => rec.ShopId == model.Id).ToList();
// обновили количество у существующих записей
foreach (var updateDoc in ShopDocuments)
{
updateDoc.Count = model.ShopDocuments[updateDoc.DocumentId].Item2;
model.ShopDocuments.Remove(updateDoc.DocumentId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var elem in model.ShopDocuments)
{
context.ShopDocuments.Add(new ShopDocument
{
Shop = shop,
Document = context.Documents.First(x => x.Id == elem.Key),
Count = elem.Value.Item2
});
context.SaveChanges();
}
_shopDocuments = null;
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmDatabaseImplement.Models
{
public class ShopDocument
{
public int Id { get; set; }
[Required]
public int DocumentId { get; set; }
[Required]
public int ShopId { get; set; }
[Required]
public int Count { get; set; }
public virtual Shop Shop { get; set; } = new();
public virtual Document Document { get; set; } = new();
}
}

View File

@ -15,12 +15,15 @@ namespace LawFirmFileImplement
private readonly string BlankFileName = "Blank.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string DocumentFileName = "Document.xml";
private readonly string ShopFileName = "Shop.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
private readonly string MessageInfoFileName = "MessageInfo.xml";
public List<Blank> Blanks { get; private set; }
public List<Order> Orders { get; private set; }
public List<Document> Documents { get; private set; }
public List<Shop> Shops { get; private set; }
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public List<MessageInfo> Messages { get; private set; }
@ -35,6 +38,7 @@ namespace LawFirmFileImplement
public void SaveBlanks() => SaveData(Blanks, BlankFileName, "Blanks", x => x.GetXElement);
public void SaveDocuments() => SaveData(Documents, DocumentFileName, "Documents", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement);
public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement);
@ -43,6 +47,7 @@ namespace LawFirmFileImplement
Blanks = LoadData(BlankFileName, "Blank", x => Blank.Create(x)!)!;
Documents = LoadData(DocumentFileName, "Document", x => Document.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Impleneter", x => Implementer.Create(x)!)!;
Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!;

View File

@ -8,6 +8,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace LawFirmFileImplement.Implements
{

View File

@ -30,10 +30,15 @@ namespace LawFirmFileImplement.Implements
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
return _source.Messages
var messages = _source.Messages
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
.Select(x => x.GetViewModel);
if (!(model.Page.HasValue && model.PageSize.HasValue))
{
return messages.ToList();
}
return messages.Skip((model.Page.Value - 1) * model.PageSize.Value).Take(model.PageSize.Value).ToList();
}
public List<MessageInfoViewModel> GetFullList()
@ -54,5 +59,16 @@ namespace LawFirmFileImplement.Implements
_source.SaveMessages();
return newMessage.GetViewModel;
}
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
var message = _source.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId));
if (message != null)
{
message.Update(model);
_source.SaveMessages();
}
return message?.GetViewModel;
}
}
}

View File

@ -0,0 +1,148 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using LawFirmFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton source;
public ShopStorage()
{
source = DataFileSingleton.GetInstance();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return source.Shops.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
return source.Shops
.Select(x => x.GetViewModel)
.Where(x => x.Name.Contains(model.Name ?? string.Empty))
.ToList();
}
public List<ShopViewModel> GetFullList()
{
return source.Shops.Select(shop => shop.GetViewModel).ToList();
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
source.Shops.Add(newShop);
source.SaveShops();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
source.SaveShops();
return shop.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
source.Shops.Remove(shop);
source.SaveShops();
return shop.GetViewModel;
}
public bool SellDocument(IDocumentModel model, int count)
{
var document = source.Documents.FirstOrDefault(x => x.Id == model.Id);
if (document == null)
{
return false;
}
var countStore = count;
var shopDocuments = source.Shops.SelectMany(shop => shop.ShopDocuments.Where(doc => doc.Value.Item1.Id == document.Id));
foreach (var doc in shopDocuments)
{
count -= doc.Value.Item2;
if (count <= 0)
{
break;
}
}
if (count > 0)
{
return false;
}
count = countStore;
foreach (var shop in source.Shops)
{
var documents = shop.ShopDocuments;
foreach (var doc in documents.Where(x => x.Value.Item1.Id == document.Id))
{
var min = Math.Min(doc.Value.Item2, count);
documents[doc.Value.Item1.Id] = (doc.Value.Item1, doc.Value.Item2 - min);
count -= min;
if (count <= 0)
{
break;
}
}
shop.Update(new ShopBindingModel
{
Id = shop.Id,
Name = shop.Name,
Adress = shop.Adress,
OpeningDate = shop.OpeningDate,
MaxCountDocuments = shop.MaxCountDocuments,
ShopDocuments = documents
});
source.SaveShops();
if (count <= 0) break;
}
return count <= 0;
}
}
}

View File

@ -96,7 +96,7 @@ namespace LawFirmFileImplement.Models
};
public XElement GetXElement => new(
"Document",
"Document",
new XAttribute("Id", Id),
new XElement("DocumentName", DocumentName),
new XElement("Price", Price.ToString()),

View File

@ -26,8 +26,12 @@ namespace LawFirmFileImplement.Models
public string Subject { get; private set; } = string.Empty;
[DataMember]
public string Body { get; private set; } = string.Empty;
[DataMember]
public bool IsReaded { get; private set; }
[DataMember]
public string? Reply { get; private set; }
public static MessageInfo? Create(MessageInfoBindingModel model)
public static MessageInfo? Create(MessageInfoBindingModel model)
{
if (model == null)
{
@ -41,7 +45,9 @@ namespace LawFirmFileImplement.Models
MessageId = model.MessageId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
};
Reply = model.Reply,
IsReaded = model.IsReaded,
};
}
public static MessageInfo? Create(XElement element)
@ -58,10 +64,22 @@ namespace LawFirmFileImplement.Models
MessageId = element.Attribute("MessageId")!.Value,
SenderName = element.Attribute("SenderName")!.Value,
DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value),
};
Reply = element.Attribute("Reply")!.Value,
IsReaded = Convert.ToBoolean(element.Attribute("IsReaded")!.Value),
};
}
public MessageInfoViewModel GetViewModel => new()
public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
Reply = model.Reply;
IsReaded = model.IsReaded;
}
public MessageInfoViewModel GetViewModel => new()
{
Body = Body,
Subject = Subject,
@ -69,7 +87,9 @@ namespace LawFirmFileImplement.Models
MessageId = MessageId,
SenderName = SenderName,
DateDelivery = DateDelivery,
};
Reply = Reply,
IsReaded = IsReaded,
};
public XElement GetXElement => new("MessageInfo",
new XAttribute("Body", Body),
@ -77,8 +97,10 @@ namespace LawFirmFileImplement.Models
new XAttribute("ClientId", ClientId),
new XAttribute("MessageId", MessageId),
new XAttribute("SenderName", SenderName),
new XAttribute("DateDelivery", DateDelivery)
);
new XAttribute("DateDelivery", DateDelivery),
new XAttribute("Reply", Reply),
new XAttribute("HasRead", IsReaded)
);
public int Id => throw new NotImplementedException();
}

View File

@ -0,0 +1,124 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace LawFirmFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string Name { get; private set; } = string.Empty;
public string Adress { get; private set; } = string.Empty;
public int MaxCountDocuments { get; private set; }
public DateTime OpeningDate { get; private set; }
public Dictionary<int, int> Documents { get; private set; } = new();
private Dictionary<int, (IDocumentModel, int)>? _shopDocuments = null;
public Dictionary<int, (IDocumentModel, int)> ShopDocuments
{
get
{
if (_shopDocuments == null)
{
var source = DataFileSingleton.GetInstance();
_shopDocuments = Documents.ToDictionary(
x => x.Key,
y => ((source.Documents.FirstOrDefault(z => z.Id == y.Key) as IDocumentModel)!, y.Value)
);
}
return _shopDocuments;
}
}
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
Name = model.Name,
Adress = model.Adress,
MaxCountDocuments = model.MaxCountDocuments,
OpeningDate = model.OpeningDate,
Documents = model.ShopDocuments.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Shop()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
Name = element.Element("Name")!.Value,
Adress = element.Element("Address")!.Value,
MaxCountDocuments = Convert.ToInt32(element.Element("MaxCountDocuments")!.Value),
OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value),
Documents= element.Element("ShopDocuments")!.Elements("ShopDocument").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)
)
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
Adress = model.Adress;
OpeningDate = model.OpeningDate;
MaxCountDocuments = model.MaxCountDocuments;
if (model.ShopDocuments.Count > 0)
{
Documents = model.ShopDocuments.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopDocuments = null;
}
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Adress = Adress,
OpeningDate = OpeningDate,
ShopDocuments = ShopDocuments,
MaxCountDocuments = MaxCountDocuments
};
public XElement GetXElement => new(
"Shop",
new XAttribute("Id", Id),
new XElement("Name", Name),
new XElement("Address", Adress),
new XElement("MaxCountDocuments", MaxCountDocuments),
new XElement("OpeningDate", OpeningDate.ToString()),
new XElement("ShopDocuments", Documents.Select (x =>
new XElement("ShopDocument",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}

View File

@ -15,6 +15,7 @@ namespace LawFirmListImplements
public List<Order> Orders { get; set; }
public List<Document> Documents { get; set; }
public List<Client> Clients { get; set; }
public List<Shop> Shops { get; set; }
public List<Implementer> Implementers { get; set; }
public List<MessageInfo> Messages { get; set; }
private DataListSingleton()
@ -22,6 +23,7 @@ namespace LawFirmListImplements
Blanks = new List<Blank>();
Orders = new List<Order>();
Documents = new List<Document>();
Shops = new List<Shop>();
Clients= new List<Client>();
Implementers = new List<Implementer>();
Messages = new List<MessageInfo>();

View File

@ -30,15 +30,29 @@ namespace LawFirmListImplements.Implements
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
List<MessageInfoViewModel> result = new();
List<MessageInfoViewModel> messages = new();
foreach (var item in _source.Messages)
{
if (item.ClientId.HasValue && item.ClientId == model.ClientId)
if (item.ClientId == model.ClientId)
{
result.Add(item.GetViewModel);
messages.Add(item.GetViewModel);
}
}
return result;
if (!(model.Page.HasValue && model.PageSize.HasValue))
{
return messages;
}
if (model.Page * model.PageSize >= messages.Count)
{
return null;
}
List<MessageInfoViewModel> filterMessages = new();
for (var i = (model.Page.Value - 1) * model.PageSize.Value; i < model.Page.Value * model.PageSize.Value; i++)
{
filterMessages.Add(messages[i]);
}
return filterMessages;
}
public List<MessageInfoViewModel> GetFullList()
@ -61,5 +75,18 @@ namespace LawFirmListImplements.Implements
_source.Messages.Add(newMessage);
return newMessage.GetViewModel;
}
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
foreach (var message in _source.Messages)
{
if (message.MessageId.Equals(model.MessageId))
{
message.Update(model);
return message.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,125 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using LawFirmListImplements.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Formats.Asn1.AsnWriter;
namespace LawFirmListImplements.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataListSingleton _source;
public ShopStorage()
{
_source = DataListSingleton.GetInstance();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
foreach (var shop in _source.Shops)
{
if ((!string.IsNullOrEmpty(model.Name) && shop.Name == model.Name) || (model.Id.HasValue && shop.Id == model.Id))
{
return shop.GetViewModel;
}
}
return null;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
var result = new List<ShopViewModel>();
if (string.IsNullOrEmpty(model.Name))
{
return result;
}
foreach (var shop in _source.Shops)
{
if (shop.Name.Contains(model.Name))
{
result.Add(shop.GetViewModel);
}
}
return result;
}
public List<ShopViewModel> GetFullList()
{
var result = new List<ShopViewModel>();
foreach (var shop in _source.Shops)
{
result.Add(shop.GetViewModel);
}
return result;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = 1;
foreach (var shop in _source.Shops)
{
if (model.Id <= shop.Id)
{
model.Id = shop.Id + 1;
}
}
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
foreach (var shop in _source.Shops)
{
if (shop.Id == model.Id)
{
shop.Update(model);
return shop.GetViewModel;
}
}
return null;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
for (int i = 0; i < _source.Shops.Count; ++i)
{
if (_source.Shops[i].Id == model.Id)
{
var element = _source.Shops[i];
_source.Shops.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public bool SellDocument(IDocumentModel model, int count)
{
throw new NotImplementedException();
}
}
}

View File

@ -22,8 +22,10 @@ namespace LawFirmListImplements.Models
public string Subject { get; private set; } = string.Empty;
public string Body { get; private set; } = string.Empty;
public bool IsReaded { get; private set; }
public string? Reply { get; private set; }
public static MessageInfo? Create(MessageInfoBindingModel model)
public static MessageInfo? Create(MessageInfoBindingModel model)
{
if (model == null)
{
@ -37,10 +39,22 @@ namespace LawFirmListImplements.Models
MessageId = model.MessageId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
};
Reply = model.Reply,
IsReaded = model.IsReaded,
};
}
public MessageInfoViewModel GetViewModel => new()
public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
Reply = model.Reply;
IsReaded = model.IsReaded;
}
public MessageInfoViewModel GetViewModel => new()
{
Body = Body,
Subject = Subject,
@ -48,7 +62,9 @@ namespace LawFirmListImplements.Models
MessageId = MessageId,
SenderName = SenderName,
DateDelivery = DateDelivery,
};
Reply = Reply,
IsReaded = IsReaded,
};
public int Id => throw new NotImplementedException();
}

View File

@ -0,0 +1,70 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using static System.Formats.Asn1.AsnWriter;
namespace LawFirmListImplements.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string Name { get; private set; } = string.Empty;
public string Adress { get; private set; } = string.Empty;
public DateTime OpeningDate { get; private set; }
public int MaxCountDocuments { get; private set; }
public Dictionary<int, (IDocumentModel, int)> ShopDocuments { get; private set; } = new();
public static Shop? Create (ShopBindingModel model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
Name = model.Name,
Adress = model.Adress,
OpeningDate = model.OpeningDate,
MaxCountDocuments = model.MaxCountDocuments,
ShopDocuments = new()
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
Adress = model.Adress;
OpeningDate = model.OpeningDate;
ShopDocuments = model.ShopDocuments;
MaxCountDocuments= model.MaxCountDocuments;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Adress = Adress,
OpeningDate = OpeningDate,
ShopDocuments = ShopDocuments,
MaxCountDocuments = MaxCountDocuments
};
}
}

View File

@ -13,8 +13,9 @@ namespace LawFirmRestApi.Controllers
private readonly ILogger _logger;
private readonly IClientLogic _logic;
private readonly IMessageInfoLogic _mailLogic;
public int pageSize = 2;
public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger<ClientController> logger)
public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger<ClientController> logger)
{
_logger = logger;
_logic = logic;
@ -65,14 +66,16 @@ namespace LawFirmRestApi.Controllers
}
[HttpGet]
public List<MessageInfoViewModel>? GetMessages(int clientId)
public List<MessageInfoViewModel>? GetMessages(int clientId, int pageNum)
{
try
{
return _mailLogic.ReadList(new MessageInfoSearchModel
{
ClientId = clientId
});
return _mailLogic.ReadList(new()
{
ClientId = clientId,
Page = pageNum,
PageSize = pageSize
});
}
catch (Exception ex)
{

View File

@ -0,0 +1,131 @@
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.ViewModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.BindingModels;
using LawFirmDataModels.Models;
namespace LawFirmRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ShopController : Controller
{
private readonly ILogger _logger;
private readonly IShopLogic _shop;
public ShopController(ILogger<ShopController> logger, IShopLogic shopLogic)
{
_logger = logger;
_shop = shopLogic;
}
[HttpGet]
public List<ShopViewModel>? GetShopList()
{
try
{
return _shop.ReadList(null);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка магазинов");
throw;
}
}
[HttpGet]
public ShopViewModel? GetShop(int shopId)
{
try
{
var shop = _shop.ReadElement(new ShopSearchModel
{
Id = shopId
});
if (shop != null)
{
List<Tuple<string, int>> docCount = new List<Tuple<string, int>>();
foreach (var doc in shop.ShopDocuments)
{
docCount.Add(new Tuple<string, int>(doc.Value.Item1.DocumentName, doc.Value.Item2));
}
shop = new()
{
Id = shop.Id,
Name = shop.Name,
Adress = shop.Adress,
OpeningDate = shop.OpeningDate,
MaxCountDocuments = shop.MaxCountDocuments,
DocumentCount = docCount
};
}
return shop;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения магазина по id={Id}",shopId);
throw;
}
}
[HttpPost]
public void CreateShop(ShopBindingModel model)
{
try
{
_shop.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания магазина");
throw;
}
}
[HttpPost]
public void UpdateShop(ShopBindingModel model)
{
try
{
_shop.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления магазина");
throw;
}
}
[HttpPost]
public void DeleteShop(ShopBindingModel model)
{
try
{
_shop.Delete(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления магазина");
throw;
}
}
[HttpPost]
public void SupplyDocumentsToShop(Tuple<ShopSearchModel,DocumentBindingModel,int> supplyRequest)
{
try
{
_shop.SupplyDocuments(supplyRequest.Item1, supplyRequest.Item2, supplyRequest.Item3);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка пополнения магазина");
throw;
}
}
}
}

View File

@ -16,11 +16,13 @@ builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IDocumentStorage, DocumentStorage>();
builder.Services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
builder.Services.AddTransient<IShopStorage, ShopStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IDocumentLogic, DocumentLogic>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
builder.Services.AddTransient<IShopLogic, ShopLogic>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

View File

@ -0,0 +1,45 @@
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
namespace LawFirmShopApp
{
public static class APIClient
{
private static readonly HttpClient _client = new();
public static bool isAuth { get; set; } = false;
public static string ConfigPassword { get; private set; } = string.Empty;
public static void Connect(IConfiguration configuration)
{
ConfigPassword = configuration["Password"];
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
}

View File

@ -0,0 +1,158 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.ViewModels;
using LawFirmShopApp.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Xml.Linq;
namespace LawFirmShopApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
if (!APIClient.isAuth)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<ShopViewModel>>($"api/shop/getshoplist"));
}
public IActionResult Privacy()
{
if (!APIClient.isAuth)
{
return Redirect("~/Home/Enter");
}
return View();
}
[HttpGet]
public IActionResult Enter()
{
return View();
}
[HttpPost]
public void Enter(string password)
{
if (string.IsNullOrEmpty(password))
{
throw new Exception("Введите пароль");
}
if (!password.Equals(APIClient.ConfigPassword))
{
throw new Exception("Неверный пароль");
}
APIClient.isAuth = true;
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public void Create(string name, string address, DateTime openingDate, int count)
{
if (!APIClient.isAuth)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (count <= 0)
{
throw new Exception("Макс. кол-во док-ов должно быть больше чем 0");
}
APIClient.PostRequest("api/shop/createshop", new ShopBindingModel
{
Name = name,
Adress = address,
OpeningDate = openingDate,
MaxCountDocuments = count,
});
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Delete()
{
ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshoplist");
return View();
}
[HttpPost]
public void Delete(int shop)
{
if (!APIClient.isAuth)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest($"api/shop/deleteshop", new ShopBindingModel { Id = shop });
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Update()
{
ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshoplist");
return View();
}
[HttpPost]
public void Update(int shop, string name, string address, DateTime openingDate, int count)
{
if (!APIClient.isAuth)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest($"api/shop/updateshop", new ShopBindingModel
{
Id = shop,
Name = name,
Adress = address,
OpeningDate = openingDate,
MaxCountDocuments = count,
}
);
Response.Redirect("Index");
}
[HttpGet]
public ShopViewModel? GetShop(int shopId)
{
return APIClient.GetRequest<ShopViewModel>($"api/shop/getshop?shopId={shopId}");
}
public IActionResult Supply()
{
ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshoplist");
ViewBag.Documents = APIClient.GetRequest<List<DocumentViewModel>>("api/main/getdocumentlist");
return View();
}
[HttpPost]
public void Supply(int shopId, int documentId, int count)
{
if (!APIClient.isAuth)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest($"api/shop/supplydocumentstoshop", (new ShopSearchModel { Id = shopId }, new DocumentBindingModel { Id = documentId }, count));
Response.Redirect("Index");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LawFirmContracts\LawFirmContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,9 @@
namespace LawFirmShopApp.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}

View File

@ -0,0 +1,30 @@
using LawFirmShopApp;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

View File

@ -0,0 +1,28 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:63201",
"sslPort": 44376
}
},
"profiles": {
"LawFirmShopApp": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7236;http://localhost:5269",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,32 @@
@{
ViewData["Title"] = "Create";
}
<div class="text-center">
<h2 class="display-4 mb-5">Создание магазина</h2>
</div>
<form method="post">
<div class="row mb-5">
<div class="col-4">Название:</div>
<div class="col-8"><input type="text" name="name" id="name" /></div>
</div>
<div class="row mb-5">
<div class="col-4">Дата открытия:</div>
<div class="col-8">
<input type="date" id="openingDate" name="openingDate" /></div>
</div>
<div class="row mb-5">
<div class="col-4">Адрес:</div>
<div class="col-8"><input type="text" id="address" name="address" /></div>
</div>
<div class="row mb-5">
<div class="col-4">Макс. документов:</div>
<div class="col-8"><input type="number" id="count" name="count" /></div>
</div>
<div class="row mb-5">
<div class="col-8">
</div>
<div class="col-4">
<input type="submit" value="Создать" class="btn btn-success" />
</div>
</div>
</form>

View File

@ -0,0 +1,17 @@
@{
ViewData["Title"] = "Delete";
}
<div class="text-center">
<h2 class="display-4">Удаление магазина</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Название:</div>
<div class="col-8">
<select id="shop" name="shop" class="form-control" asp-items="@(new SelectList(@ViewBag.Shops,"Id", "Name"))"></select>
</div>
</div>
<div class="col-4">
<input type="submit" value="Удалить" class="btn btn-danger" />
</div>
</form>

View File

@ -0,0 +1,15 @@
@{
ViewData["Title"] = "Enter";
}
<div class="text-center mb-5">
<h2 class="display-4">Авторизация</h2>
</div>
<form method="post">
<div class="row text-center mb-5">
<div class="mb-3 h4">Введите пароль:</div>
<div><input type="password" name="password"/></div>
</div>
<div class="row text-center">
<div><input type="submit" value="Войти" class="btn btn-success ps-5 pe-5" /></div>
</div>
</form>

View File

@ -0,0 +1,57 @@
@using LawFirmContracts.ViewModels
@model List<ShopViewModel>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Магазины</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p >
<a class="text-decoration-none me-3 text-black h5" asp-action="Create">Создать магазин</a>
<a class="text-decoration-none me-3 text-black h5" asp-action="Update">Изменить магазин</a>
<a class="text-decoration-none me-3 text-black h5" asp-action="Supply">Пополнить магазин</a>
<a class="text-decoration-none text-black h5" asp-action="Delete">Удалить магазин</a>
</p>
<table class="table">
<thead>
<tr>
<th>Номер</th>
<th>Название</th>
<th>Адрес</th>
<th>Дата открытия</th>
<th>Макс. док-ов</th>
</tr>
</thead>
<tbody>
@foreach (var shop in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => shop.Id)
</td>
<td>
@Html.DisplayFor(modelItem => shop.Name)
</td>
<td>
@Html.DisplayFor(modelItem => shop.Adress)
</td>
<td>
@Html.DisplayFor(modelItem => shop.OpeningDate)
</td>
<td>
@Html.DisplayFor(modelItem => shop.MaxCountDocuments)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,6 @@
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>

Some files were not shown because too many files have changed in this diff Show More