This commit is contained in:
Максим Сергунов 2023-06-01 23:00:14 +04:00
parent 6e3d43e265
commit f0f89c2720
5 changed files with 338 additions and 284 deletions

View File

@ -46,7 +46,7 @@ namespace GiftShopBusinessLogic.BusinessLogics
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
_logger.LogInformation("ReadElement. ClientFIO:{ClientFIO}. Id:{ Id}", model.ClientFIO, model.Id); _logger.LogInformation("ReadElement. ClientFIO:{ClientFIO}. Email: {Email}. Id:{ Id}", model.ClientFIO, model.Email, model.Id);
var element = _clientStorage.GetElement(model); var element = _clientStorage.GetElement(model);
if (element == null) if (element == null)
{ {
@ -59,7 +59,7 @@ namespace GiftShopBusinessLogic.BusinessLogics
public List<ClientViewModel>? ReadList(ClientSearchModel? model) public List<ClientViewModel>? ReadList(ClientSearchModel? model)
{ {
_logger.LogInformation("ReadList. ClientFIO:{ClientFIO}. Id:{Id}", model?.ClientFIO, model?.Id); _logger.LogInformation("ReadList. ClientFIO: {ClientName}. Email: {Email}. Id: {Id}.", model?.ClientFIO, model?.Email, model?.Id);
var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model); var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model);
if (list == null) if (list == null)
{ {
@ -100,13 +100,13 @@ namespace GiftShopBusinessLogic.BusinessLogics
} }
if (string.IsNullOrEmpty(model.Password)) if (string.IsNullOrEmpty(model.Password))
{ {
throw new ArgumentNullException("У клиента отсутствует пароль", nameof(model.Email)); throw new ArgumentNullException("У клиента отсутствует пароль", nameof(model.Password));
} }
if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$")) if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase))
{ {
throw new ArgumentException("Неправильно введенный email", nameof(model.Email)); throw new ArgumentException("Неправильно введенный email", nameof(model.Email));
} }
if (!Regex.IsMatch(model.Password, @"^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$") || model.Password.Length < 10 || model.Password.Length > 50) if (model.Password.Length < 10 || model.Password.Length > 50)
{ {
throw new ArgumentException("Неправильно введенный пароль", nameof(model.Password)); throw new ArgumentException("Неправильно введенный пароль", nameof(model.Password));
} }

View File

@ -38,15 +38,15 @@ namespace GiftShopBusinessLogic.BusinessLogics
} }
model.Status = OrderStatus.Принят; model.Status = OrderStatus.Принят;
var result = _orderStorage.Insert(model);
if (_orderStorage.Insert(model) == null) if (result == null)
{ {
model.Status = OrderStatus.Неизвестен; model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
return false; return false;
} }
SendOrderMessage(result.ClientId, $"Магазин подарков, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят");
return true; return true;
} }
public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus)
@ -79,12 +79,15 @@ namespace GiftShopBusinessLogic.BusinessLogics
model.Sum = vmodel.Sum; model.Sum = vmodel.Sum;
model.Count = vmodel.Count; model.Count = vmodel.Count;
if (_orderStorage.Update(model) == null) var result = _orderStorage.Update(model);
if (result == null)
{ {
_logger.LogWarning("Update operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
SendOrderMessage(result.ClientId, $"Магазин подарков, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}");
return true; return true;
} }

View File

@ -1,145 +1,169 @@
namespace GiftShopView namespace GiftShopView
{ {
partial class FormCreateOrder partial class FormCreateOrder
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
/// </summary> /// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
labelGift = new Label(); labelGift = new Label();
labelCount = new Label(); labelCount = new Label();
labelSum = new Label(); labelSum = new Label();
comboBoxGift = new ComboBox(); comboBoxGift = new ComboBox();
textBoxCount = new TextBox(); textBoxCount = new TextBox();
textBoxSum = new TextBox(); textBoxSum = new TextBox();
buttonSave = new Button(); buttonSave = new Button();
buttonCancel = new Button(); buttonCancel = new Button();
SuspendLayout(); labelClient = new Label();
// comboBoxClient = new ComboBox();
// labelGift SuspendLayout();
// //
labelGift.AutoSize = true; // labelGift
labelGift.Location = new Point(34, 44); //
labelGift.Name = "labelGift"; labelGift.AutoSize = true;
labelGift.Size = new Size(71, 20); labelGift.Location = new Point(34, 44);
labelGift.TabIndex = 0; labelGift.Name = "labelGift";
labelGift.Text = "Изделие:"; labelGift.Size = new Size(71, 20);
// labelGift.TabIndex = 0;
// labelCount labelGift.Text = "Изделие:";
// //
labelCount.AutoSize = true; // labelCount
labelCount.Location = new Point(34, 112); //
labelCount.Name = "labelCount"; labelCount.AutoSize = true;
labelCount.Size = new Size(93, 20); labelCount.Location = new Point(34, 138);
labelCount.TabIndex = 1; labelCount.Name = "labelCount";
labelCount.Text = "Количество:"; labelCount.Size = new Size(93, 20);
// labelCount.TabIndex = 1;
// labelSum labelCount.Text = "Количество:";
// //
labelSum.AutoSize = true; // labelSum
labelSum.Location = new Point(34, 171); //
labelSum.Name = "labelSum"; labelSum.AutoSize = true;
labelSum.Size = new Size(58, 20); labelSum.Location = new Point(34, 187);
labelSum.TabIndex = 2; labelSum.Name = "labelSum";
labelSum.Text = "Сумма:"; labelSum.Size = new Size(58, 20);
// labelSum.TabIndex = 2;
// comboBoxGift labelSum.Text = "Сумма:";
// //
comboBoxGift.DropDownStyle = ComboBoxStyle.DropDownList; // comboBoxGift
comboBoxGift.FormattingEnabled = true; //
comboBoxGift.Location = new Point(141, 41); comboBoxGift.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxGift.Name = "comboBoxGift"; comboBoxGift.FormattingEnabled = true;
comboBoxGift.Size = new Size(369, 28); comboBoxGift.Location = new Point(141, 41);
comboBoxGift.TabIndex = 3; comboBoxGift.Name = "comboBoxGift";
comboBoxGift.SelectedIndexChanged += ComboBoxGift_SelectedIndexChanged; comboBoxGift.Size = new Size(369, 28);
// comboBoxGift.TabIndex = 3;
// textBoxCount comboBoxGift.SelectedIndexChanged += ComboBoxGift_SelectedIndexChanged;
// //
textBoxCount.Location = new Point(141, 109); // textBoxCount
textBoxCount.Name = "textBoxCount"; //
textBoxCount.Size = new Size(369, 27); textBoxCount.Location = new Point(141, 135);
textBoxCount.TabIndex = 4; textBoxCount.Name = "textBoxCount";
textBoxCount.TextChanged += TextBoxCount_TextChanged; textBoxCount.Size = new Size(369, 27);
// textBoxCount.TabIndex = 4;
// textBoxSum textBoxCount.TextChanged += TextBoxCount_TextChanged;
// //
textBoxSum.Location = new Point(141, 171); // textBoxSum
textBoxSum.Name = "textBoxSum"; //
textBoxSum.ReadOnly = true; textBoxSum.Location = new Point(141, 187);
textBoxSum.Size = new Size(369, 27); textBoxSum.Name = "textBoxSum";
textBoxSum.TabIndex = 5; textBoxSum.ReadOnly = true;
// textBoxSum.Size = new Size(369, 27);
// buttonSave textBoxSum.TabIndex = 5;
// //
buttonSave.Location = new Point(197, 245); // buttonSave
buttonSave.Name = "buttonSave"; //
buttonSave.Size = new Size(144, 45); buttonSave.Location = new Point(197, 245);
buttonSave.TabIndex = 6; buttonSave.Name = "buttonSave";
buttonSave.Text = "Сохранить"; buttonSave.Size = new Size(144, 45);
buttonSave.UseVisualStyleBackColor = true; buttonSave.TabIndex = 6;
buttonSave.Click += ButtonSave_Click; buttonSave.Text = "Сохранить";
// buttonSave.UseVisualStyleBackColor = true;
// buttonCancel buttonSave.Click += ButtonSave_Click;
// //
buttonCancel.Location = new Point(384, 245); // buttonCancel
buttonCancel.Name = "buttonCancel"; //
buttonCancel.Size = new Size(126, 45); buttonCancel.Location = new Point(384, 245);
buttonCancel.TabIndex = 7; buttonCancel.Name = "buttonCancel";
buttonCancel.Text = "Отмена"; buttonCancel.Size = new Size(126, 45);
buttonCancel.UseVisualStyleBackColor = true; buttonCancel.TabIndex = 7;
buttonCancel.Click += ButtonCancel_Click; buttonCancel.Text = "Отмена";
// buttonCancel.UseVisualStyleBackColor = true;
// FormCreateOrder buttonCancel.Click += ButtonCancel_Click;
// //
AutoScaleDimensions = new SizeF(8F, 20F); // labelClient
AutoScaleMode = AutoScaleMode.Font; //
ClientSize = new Size(539, 308); labelClient.AutoSize = true;
Controls.Add(buttonCancel); labelClient.Location = new Point(34, 92);
Controls.Add(buttonSave); labelClient.Name = "labelClient";
Controls.Add(textBoxSum); labelClient.Size = new Size(61, 20);
Controls.Add(textBoxCount); labelClient.TabIndex = 8;
Controls.Add(comboBoxGift); labelClient.Text = "Клиент:";
Controls.Add(labelSum); //
Controls.Add(labelCount); // comboBoxClient
Controls.Add(labelGift); //
Name = "FormCreateOrder"; comboBoxClient.DropDownStyle = ComboBoxStyle.DropDownList;
Text = "Заказ"; comboBoxClient.FormattingEnabled = true;
Load += FormCreateOrder_Load; comboBoxClient.Location = new Point(141, 89);
ResumeLayout(false); comboBoxClient.Name = "comboBoxClient";
PerformLayout(); comboBoxClient.Size = new Size(369, 28);
} comboBoxClient.TabIndex = 9;
//
// FormCreateOrder
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(539, 308);
Controls.Add(comboBoxClient);
Controls.Add(labelClient);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxSum);
Controls.Add(textBoxCount);
Controls.Add(comboBoxGift);
Controls.Add(labelSum);
Controls.Add(labelCount);
Controls.Add(labelGift);
Name = "FormCreateOrder";
Text = "Заказ";
Load += FormCreateOrder_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion #endregion
private Label labelGift; private Label labelGift;
private Label labelCount; private Label labelCount;
private Label labelSum; private Label labelSum;
private ComboBox comboBoxGift; private ComboBox comboBoxGift;
private TextBox textBoxCount; private TextBox textBoxCount;
private TextBox textBoxSum; private TextBox textBoxSum;
private Button buttonSave; private Button buttonSave;
private Button buttonCancel; private Button buttonCancel;
} private Label labelClient;
private ComboBox comboBoxClient;
}
} }

View File

@ -5,123 +5,145 @@ using Microsoft.Extensions.Logging;
namespace GiftShopView namespace GiftShopView
{ {
public partial class FormCreateOrder : Form public partial class FormCreateOrder : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IGiftLogic _logicP; private readonly IGiftLogic _logicP;
private readonly IOrderLogic _logicO; private readonly IOrderLogic _logicO;
public FormCreateOrder(ILogger<FormCreateOrder> logger, IGiftLogic logicP, IOrderLogic logicO) private readonly IClientLogic _logicC;
{
InitializeComponent();
_logger = logger;
_logicP = logicP;
_logicO = logicO;
}
private void FormCreateOrder_Load(object sender, EventArgs e) public FormCreateOrder(ILogger<FormCreateOrder> logger, IGiftLogic logicP, IOrderLogic logicO, IClientLogic logicC)
{ {
_logger.LogInformation("Загрузка изделий для заказа"); InitializeComponent();
LoadData(); _logger = logger;
} _logicP = logicP;
_logicO = logicO;
_logicC = logicC;
}
private void LoadData() private void FormCreateOrder_Load(object sender, EventArgs e)
{ {
_logger.LogInformation("Загрузка изделий для заказа"); _logger.LogInformation("Загрузка изделий для заказа");
try LoadData();
{ }
var list = _logicP.ReadList(null);
if (list != null)
{
comboBoxGift.DisplayMember = "GiftName";
comboBoxGift.ValueMember = "ID";
comboBoxGift.DataSource = list;
comboBoxGift.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CalcSum() private void LoadData()
{ {
if (comboBoxGift.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text)) _logger.LogInformation("Загрузка изделий для заказа");
{ try
try {
{ var list = _logicP.ReadList(null);
int id = Convert.ToInt32(comboBoxGift.SelectedValue); if (list != null)
var product = _logicP.ReadElement(new GiftSearchModel {
{ comboBoxGift.DisplayMember = "GiftName";
Id = id comboBoxGift.ValueMember = "ID";
}); comboBoxGift.DataSource = list;
int count = Convert.ToInt32(textBoxCount.Text); comboBoxGift.SelectedItem = null;
textBoxSum.Text = Math.Round(count * (product?.Price ?? 0), 2).ToString(); }
_logger.LogInformation("Расчет суммы заказа"); }
} catch (Exception ex)
catch (Exception ex) {
{ _logger.LogError(ex, "Ошибка загрузки списка изделий");
_logger.LogError(ex, "Ошибка расчета суммы заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); }
} _logger.LogInformation("Загрузка клиентов для заказа");
} try
} {
var list = _logicC.ReadList(null);
if (list != null)
{
comboBoxClient.DisplayMember = "Клиент";
comboBoxClient.ValueMember = "Id";
comboBoxClient.DataSource = list.Select(c => c.ClientFIO).ToList();
comboBoxClient.SelectedItem = null;
}
private void TextBoxCount_TextChanged(object sender, EventArgs e) }
{ catch (Exception ex)
CalcSum(); {
} _logger.LogError(ex, "Ошибка загрузки списка клиентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ComboBoxGift_SelectedIndexChanged(object sender, EventArgs e) private void CalcSum()
{ {
CalcSum(); if (comboBoxGift.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text))
} {
try
{
int id = Convert.ToInt32(comboBoxGift.SelectedValue);
var product = _logicP.ReadElement(new GiftSearchModel
{
Id = id
});
int count = Convert.ToInt32(textBoxCount.Text);
textBoxSum.Text = Math.Round(count * (product?.Price ?? 0), 2).ToString();
_logger.LogInformation("Расчет суммы заказа");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка расчета суммы заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e) private void TextBoxCount_TextChanged(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(textBoxCount.Text)) CalcSum();
{ }
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxGift.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
GiftId = Convert.ToInt32(comboBoxGift.SelectedValue),
GiftName = comboBoxGift.Text,
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.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) private void ComboBoxGift_SelectedIndexChanged(object sender, EventArgs e)
{ {
DialogResult = DialogResult.Cancel; CalcSum();
Close(); }
}
} private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxGift.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
GiftId = Convert.ToInt32(comboBoxGift.SelectedValue),
GiftName = comboBoxGift.Text,
ClientId = Convert.ToInt32(comboBoxClient.SelectedIndex),
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.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

@ -6,36 +6,41 @@ namespace GiftShopView
public partial class FormMails : Form public partial class FormMails : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic; private readonly IMessageInfoLogic _logic;
public FormMails(ILogger<FormMails> logger, IMessageInfoLogic logic) public FormMails(ILogger<FormMails> logger, IMessageInfoLogic logic)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_logic = logic; _logic = logic;
} }
private void FormMails_Load(object sender, EventArgs e) private void LoadData()
{ {
try try
{ {
var list = _logic.ReadList(null); var list = _logic.ReadList(null);
if (list != null) if (list != null)
{ {
dataGridView.DataSource = list; dataGridView.DataSource = list;
dataGridView.Columns["ClientId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["MessageId"].Visible = false; dataGridView.Columns["MessageId"].Visible = false;
dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
} }
_logger.LogInformation("Загрузка писем"); _logger.LogInformation("Загрузка писем");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка загрузки писем"); _logger.LogError(ex, "Ошибка загрузки писем");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error); MessageBoxIcon.Error);
} }
} }
private void FormMails_Load(object sender, EventArgs e)
{
LoadData();
}
} }
} }