diff --git a/.gitignore b/.gitignore index ca1c7a3..52737dc 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,9 @@ # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs +# dll файлы +*.dll + # Mono auto generated files mono_crash.* diff --git a/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..ef9e706 --- /dev/null +++ b/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,64 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.BusinessLogicsContracts; +using IceCreamShopContracts.SearchModels; +using IceCreamShopContracts.StoragesContracts; +using IceCreamShopContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace IceCreamBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage MessageInfoStorage) + { + _logger = logger; + _messageInfoStorage = MessageInfoStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public MessageInfoViewModel? ReadElement(MessageInfoSearchModel model) + { + var res = _messageInfoStorage.GetElement(model); + if (res == null) + { + _logger.LogWarning("Read element operation failed"); + return null; + } + return res; + } + + public bool Update(MessageInfoBindingModel model) + { + if (_messageInfoStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId); + var list = (model == null) ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + } +} diff --git a/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/OrderLogic.cs b/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/OrderLogic.cs index 8c47637..7f262ff 100644 --- a/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/IceCreamShop/IceCreamBusinessLogic/BusinessLogics/OrderLogic.cs @@ -10,6 +10,7 @@ using IceCreamShopContracts.SearchModels; using IceCreamShopContracts.StoragesContracts; using IceCreamShopContracts.ViewModels; using AbstractIceCreamShopDataModels.Enums; +using IceCreamBusinessLogic.MailWorker; using AbstractIceCreamShopDataModels.Models; namespace IceCreamBusinessLogic.BusinessLogics @@ -18,20 +19,23 @@ namespace IceCreamBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; private readonly IShopStorage _shopStorage; private readonly IShopLogic _shopLogic; private readonly IIceCreamStorage _iceCreamStorage; - public OrderLogic(IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IIceCreamStorage iceCreamStorage, ILogger logger) - { - _orderStorage = orderStorage; - _shopStorage = shopStorage; - _logger = logger; - _shopLogic = shopLogic; - _iceCreamStorage = iceCreamStorage; - } + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IIceCreamStorage icecreamStorage, IShopLogic shopLogic, IClientLogic clientLogic, AbstractMailWorker mailWorker) + { + _logger = logger; + _shopLogic = shopLogic; + _iceCreamStorage = icecreamStorage; + _orderStorage = orderStorage; + _mailWorker = mailWorker; + _clientLogic = clientLogic; + } - public bool CreateOrder(OrderBindingModel model) + public bool CreateOrder(OrderBindingModel model) { CheckModel(model); if(model.Status != OrderStatus.Неизвестен) @@ -40,14 +44,15 @@ namespace IceCreamBusinessLogic.BusinessLogics return false; } model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) - { - model.Status = OrderStatus.Неизвестен; - _logger.LogWarning("Insert operation failed"); - return false; - } - return true; - } + var result = _orderStorage.Insert(model); + if (result == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + SendOrderStatusMail(result.ClientId, $"Новый заказ создан. Номер заказа #{result.Id}", $"Заказ #{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); + return true; + } public bool DeliveryOrder(OrderBindingModel model) { @@ -102,130 +107,132 @@ namespace IceCreamBusinessLogic.BusinessLogics _logger.LogInformation("Order. OrderID:{Id}.Sum:{ Sum}. DocumentId: { DocumentId}", model.Id, model.Sum, model.IceCreamId); } - public bool SetNewStatus(OrderBindingModel rawModel, OrderStatus newStatus) - { - var viewModel = _orderStorage.GetElement(new OrderSearchModel - { - Id = rawModel.Id - }); + public bool SetNewStatus(OrderBindingModel rawModel, OrderStatus newStatus) + { + var viewModel = _orderStorage.GetElement(new OrderSearchModel + { + Id = rawModel.Id + }); - if (viewModel == null) - { - _logger.LogWarning("Order model not found"); - return false; - } + if (viewModel == null) + { + _logger.LogWarning("Order model not found"); + return false; + } - OrderBindingModel model = new OrderBindingModel - { - Id = viewModel.Id, - IceCreamId = viewModel.IceCreamId, - Status = viewModel.Status, - DateCreate = viewModel.DateCreate, - DateImplement = viewModel.DateImplement, - Count = viewModel.Count, - Sum = viewModel.Sum, - ImplementerId = viewModel.ImplementerId - }; - if (rawModel.ImplementerId.HasValue) - { - model.ImplementerId = rawModel.ImplementerId; - } + OrderBindingModel model = new OrderBindingModel + { + Id = viewModel.Id, + IceCreamId = viewModel.IceCreamId, + Status = viewModel.Status, + DateCreate = viewModel.DateCreate, + DateImplement = viewModel.DateImplement, + Count = viewModel.Count, + Sum = viewModel.Sum, + ImplementerId = viewModel.ImplementerId + }; + if (rawModel.ImplementerId.HasValue) + { + model.ImplementerId = rawModel.ImplementerId; + } - CheckModel(model); - if (model.Status + 1 != newStatus && model.Status != OrderStatus.Ожидается) - { - _logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Order status incorrect."); - return false; - } + CheckModel(model); + 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 icecream = _iceCreamStorage.GetElement(new IceCreamSearchModel() { Id = model.IceCreamId }); - if (icecream == null) - { - _logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Icecream not found."); - return false; - } - if (CheckSupply(icecream, model.Count) == false) - { - _logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Shop supply error."); - model.Status = OrderStatus.Ожидается; - _orderStorage.Update(model); - return false; - } - } + if (newStatus == OrderStatus.Готов) + { + var icecream = _iceCreamStorage.GetElement(new IceCreamSearchModel() { Id = model.IceCreamId }); + if (icecream == null) + { + _logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Icecream not found."); + return false; + } + if (CheckSupply(icecream, 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; - if (_orderStorage.Update(model) == null) - { - model.Status--; - _logger.LogWarning("Update operation failed"); - return false; - } - return true; - } + model.Status = newStatus; + if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; + var result = _orderStorage.Update(model); + if (result == null) + { + model.Status--; + _logger.LogWarning("Update operation failed"); + return false; + } + SendOrderStatusMail(result.ClientId, $"Изменен статус заказа #{result.Id}", $"Заказ #{result.Id} изменен статус на {result.Status}"); + return true; + } - public bool CheckSupply(IIceCreamModel model, int count) - { - if (count <= 0) - { - _logger.LogWarning("Check then supply operation error. icecream count < 0."); - return false; - } + public bool CheckSupply(IIceCreamModel model, int count) + { + if (count <= 0) + { + _logger.LogWarning("Check then supply operation error. icecream count < 0."); + return false; + } - int freeSpace = 0; - foreach (var shop in _shopStorage.GetFullList()) - { - freeSpace += shop.IceCreamMaxCount; - foreach (var icecream in shop.ShopIceCreams) - { - freeSpace -= icecream.Value.Item2; - } - } + int freeSpace = 0; + foreach (var shop in _shopStorage.GetFullList()) + { + freeSpace += shop.IceCreamMaxCount; + foreach (var icecream in shop.ShopIceCreams) + { + freeSpace -= icecream.Value.Item2; + } + } - if (freeSpace - count < 0) - { - _logger.LogWarning("Check then supply operation error. There's no place for new icecreams in shops."); - return false; - } + if (freeSpace - count < 0) + { + _logger.LogWarning("Check then supply operation error. There's no place for new icecreams in shops."); + return false; + } - foreach (var shop in _shopStorage.GetFullList()) - { - freeSpace = shop.IceCreamMaxCount; - foreach (var icecream in shop.ShopIceCreams) - { - freeSpace -= icecream.Value.Item2; - } - if (freeSpace == 0) - { - continue; - } - if (freeSpace - count >= 0) - { - if (_shopLogic.SupplyIceCreams(new() { Id = shop.Id }, model, count)) count = 0; - else - { - _logger.LogWarning("Supply error"); - return false; - } - } - if (freeSpace - count < 0) - { - if (_shopLogic.SupplyIceCreams(new() { Id = shop.Id }, model, freeSpace)) count -= freeSpace; - else - { - _logger.LogWarning("Supply error"); - return false; - } - } - if (count <= 0) - { - return true; - } - } - return false; - } + foreach (var shop in _shopStorage.GetFullList()) + { + freeSpace = shop.IceCreamMaxCount; + foreach (var icecream in shop.ShopIceCreams) + { + freeSpace -= icecream.Value.Item2; + } + if (freeSpace == 0) + { + continue; + } + if (freeSpace - count >= 0) + { + if (_shopLogic.SupplyIceCreams(new() { Id = shop.Id }, model, count)) count = 0; + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (freeSpace - count < 0) + { + if (_shopLogic.SupplyIceCreams(new() { Id = shop.Id }, model, freeSpace)) count -= freeSpace; + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (count <= 0) + { + return true; + } + } + return false; + } public OrderViewModel? ReadElement(OrderSearchModel model) { @@ -243,5 +250,21 @@ namespace IceCreamBusinessLogic.BusinessLogics _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); return element; } - } + + private bool SendOrderStatusMail(int clientId, string subject, string text) + { + var client = _clientLogic.ReadElement(new() { Id = clientId }); + if (client == null) + { + return false; + } + _mailWorker.MailSendAsync(new() + { + MailAddress = client.Email, + Subject = subject, + Text = text + }); + return true; + } + } } diff --git a/IceCreamShop/IceCreamBusinessLogic/IceCreamBusinessLogic.csproj b/IceCreamShop/IceCreamBusinessLogic/IceCreamBusinessLogic.csproj index b70c7ba..24e35c5 100644 --- a/IceCreamShop/IceCreamBusinessLogic/IceCreamBusinessLogic.csproj +++ b/IceCreamShop/IceCreamBusinessLogic/IceCreamBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/IceCreamShop/IceCreamBusinessLogic/MailWorker/AbstractMailWorker.cs b/IceCreamShop/IceCreamBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..9c6e437 --- /dev/null +++ b/IceCreamShop/IceCreamBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,97 @@ +using IceCreamBusinessLogic.BusinessLogics; +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace IceCreamBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + + protected string _mailPassword = string.Empty; + + protected string _smtpClientHost = string.Empty; + + protected int _smtpClientPort; + + protected string _popHost = string.Empty; + + protected int _popPort; + + private readonly IMessageInfoLogic _messageInfoLogic; + + private readonly IClientLogic _clientLogic; + + private readonly ILogger _logger; + + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + _clientLogic = clientLogic; + } + + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + + if (_messageInfoLogic == null) + { + return; + } + + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id; + _messageInfoLogic.Create(mail); + } + } + + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + + protected abstract Task> ReceiveMailAsync(); + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamBusinessLogic/MailWorker/MailKitWorker.cs b/IceCreamShop/IceCreamBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..896cd31 --- /dev/null +++ b/IceCreamShop/IceCreamBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,78 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.BusinessLogicsContracts; +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using System.Net; +using System.Net.Mail; +using System.Text; + +namespace IceCreamBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) : base(logger, messageInfoLogic, clientLogic) { } + + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShop/App.config b/IceCreamShop/IceCreamShop/App.config new file mode 100644 index 0000000..8952286 --- /dev/null +++ b/IceCreamShop/IceCreamShop/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/IceCreamShop/IceCreamShop/FormMain.Designer.cs b/IceCreamShop/IceCreamShop/FormMain.Designer.cs index f5a299b..ec07220 100644 --- a/IceCreamShop/IceCreamShop/FormMain.Designer.cs +++ b/IceCreamShop/IceCreamShop/FormMain.Designer.cs @@ -1,33 +1,33 @@ namespace IceCreamShopView { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + 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 - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { this.buttonUpdate = new System.Windows.Forms.Button(); this.buttonSetToFinish = new System.Windows.Forms.Button(); this.buttonCreateOrder = new System.Windows.Forms.Button(); @@ -47,6 +47,7 @@ this.shopWorkloadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ordersByDateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.DoWorkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.MailToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.buttonSupplyShop = new System.Windows.Forms.Button(); this.SellIceCreamButton = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); @@ -55,7 +56,7 @@ // // buttonUpdate // - this.buttonUpdate.Location = new System.Drawing.Point(1231, 392); + this.buttonUpdate.Location = new System.Drawing.Point(1235, 149); this.buttonUpdate.Name = "buttonUpdate"; this.buttonUpdate.Size = new System.Drawing.Size(194, 49); this.buttonUpdate.TabIndex = 13; @@ -65,7 +66,7 @@ // // buttonSetToFinish // - this.buttonSetToFinish.Location = new System.Drawing.Point(1231, 90); + this.buttonSetToFinish.Location = new System.Drawing.Point(1235, 93); this.buttonSetToFinish.Name = "buttonSetToFinish"; this.buttonSetToFinish.Size = new System.Drawing.Size(194, 49); this.buttonSetToFinish.TabIndex = 12; @@ -75,7 +76,7 @@ // // buttonCreateOrder // - this.buttonCreateOrder.Location = new System.Drawing.Point(1231, 35); + this.buttonCreateOrder.Location = new System.Drawing.Point(1235, 39); this.buttonCreateOrder.Name = "buttonCreateOrder"; this.buttonCreateOrder.Size = new System.Drawing.Size(194, 49); this.buttonCreateOrder.TabIndex = 9; @@ -90,7 +91,7 @@ this.dataGridView.Name = "dataGridView"; this.dataGridView.RowHeadersWidth = 51; this.dataGridView.RowTemplate.Height = 29; - this.dataGridView.Size = new System.Drawing.Size(1202, 407); + this.dataGridView.Size = new System.Drawing.Size(1215, 407); this.dataGridView.TabIndex = 8; // // menuStrip @@ -99,11 +100,12 @@ this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.справочникиToolStripMenuItem, this.отчетыToolStripMenuItem, - this.DoWorkToolStripMenuItem}); + this.DoWorkToolStripMenuItem, + this.MailToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; this.menuStrip.Padding = new System.Windows.Forms.Padding(6, 3, 0, 3); - this.menuStrip.Size = new System.Drawing.Size(1433, 30); + this.menuStrip.Size = new System.Drawing.Size(1441, 30); this.menuStrip.TabIndex = 7; this.menuStrip.Text = "Справочники"; // @@ -172,21 +174,18 @@ this.iceCreamComponentsToolStripMenuItem.Name = "iceCreamComponentsToolStripMenuItem"; this.iceCreamComponentsToolStripMenuItem.Size = new System.Drawing.Size(299, 26); this.iceCreamComponentsToolStripMenuItem.Text = "Список мороженых"; - this.iceCreamComponentsToolStripMenuItem.Click += new System.EventHandler(this.IceCreamsToolStripMenuItem_Click); // // iceCreamToolStripMenuItem // this.iceCreamToolStripMenuItem.Name = "iceCreamToolStripMenuItem"; this.iceCreamToolStripMenuItem.Size = new System.Drawing.Size(299, 26); this.iceCreamToolStripMenuItem.Text = "Мороженые с компонентами"; - this.iceCreamToolStripMenuItem.Click += new System.EventHandler(this.IceCreamComponentsToolStripMenuItem_Click); // // ordersToolStripMenuItem // this.ordersToolStripMenuItem.Name = "ordersToolStripMenuItem"; this.ordersToolStripMenuItem.Size = new System.Drawing.Size(299, 26); this.ordersToolStripMenuItem.Text = "Список заказов"; - this.ordersToolStripMenuItem.Click += new System.EventHandler(this.OrdersToolStripMenuItem_Click); // // listShopsToolStripMenuItem // @@ -216,11 +215,18 @@ this.DoWorkToolStripMenuItem.Text = "Запуск работ"; this.DoWorkToolStripMenuItem.Click += new System.EventHandler(this.DoWorkToolStripMenuItem_Click); // + // MailToolStripMenuItem + // + this.MailToolStripMenuItem.Name = "MailToolStripMenuItem"; + this.MailToolStripMenuItem.Size = new System.Drawing.Size(77, 24); + this.MailToolStripMenuItem.Text = "Письма"; + this.MailToolStripMenuItem.Click += new System.EventHandler(this.MailToolStripMenuItem_Click); + // // buttonSupplyShop // - this.buttonSupplyShop.Location = new System.Drawing.Point(1231, 292); + this.buttonSupplyShop.Location = new System.Drawing.Point(1235, 303); this.buttonSupplyShop.Name = "buttonSupplyShop"; - this.buttonSupplyShop.Size = new System.Drawing.Size(194, 44); + this.buttonSupplyShop.Size = new System.Drawing.Size(194, 49); this.buttonSupplyShop.TabIndex = 14; this.buttonSupplyShop.Text = "Пополнение магазина"; this.buttonSupplyShop.UseVisualStyleBackColor = true; @@ -228,9 +234,9 @@ // // SellIceCreamButton // - this.SellIceCreamButton.Location = new System.Drawing.Point(1231, 248); + this.SellIceCreamButton.Location = new System.Drawing.Point(1235, 358); this.SellIceCreamButton.Name = "SellIceCreamButton"; - this.SellIceCreamButton.Size = new System.Drawing.Size(194, 40); + this.SellIceCreamButton.Size = new System.Drawing.Size(194, 49); this.SellIceCreamButton.TabIndex = 15; this.SellIceCreamButton.Text = "Продажа мороженого"; this.SellIceCreamButton.UseVisualStyleBackColor = true; @@ -240,7 +246,7 @@ // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1433, 467); + this.ClientSize = new System.Drawing.Size(1441, 463); this.Controls.Add(this.SellIceCreamButton); this.Controls.Add(this.buttonSupplyShop); this.Controls.Add(this.buttonUpdate); @@ -248,7 +254,7 @@ this.Controls.Add(this.buttonCreateOrder); this.Controls.Add(this.dataGridView); this.Controls.Add(this.menuStrip); - this.Margin = new System.Windows.Forms.Padding(3, 5, 3, 5); + this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.Name = "FormMain"; this.Text = "Магазин мороженого"; this.Load += new System.EventHandler(this.FormMain_Load); @@ -258,30 +264,31 @@ this.ResumeLayout(false); this.PerformLayout(); - } + } - #endregion + #endregion - private Button buttonUpdate; - private Button buttonSetToFinish; - private Button buttonCreateOrder; - private DataGridView dataGridView; - private MenuStrip menuStrip; - private ToolStripMenuItem справочникиToolStripMenuItem; - private ToolStripMenuItem компонентыToolStripMenuItem; - private ToolStripMenuItem мороженоеToolStripMenuItem; - private ToolStripMenuItem отчетыToolStripMenuItem; - private ToolStripMenuItem iceCreamComponentsToolStripMenuItem; - private ToolStripMenuItem iceCreamToolStripMenuItem; - private ToolStripMenuItem ordersToolStripMenuItem; - private ToolStripMenuItem клиентыToolStripMenuItem; - private ToolStripMenuItem ImplementersToolStripMenuItem; - private ToolStripMenuItem DoWorkToolStripMenuItem; - private ToolStripMenuItem магазиныToolStripMenuItem; + private Button buttonUpdate; + private Button buttonSetToFinish; + private Button buttonCreateOrder; + private DataGridView dataGridView; + private MenuStrip menuStrip; + private ToolStripMenuItem справочникиToolStripMenuItem; + private ToolStripMenuItem компонентыToolStripMenuItem; + private ToolStripMenuItem мороженоеToolStripMenuItem; + private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem iceCreamComponentsToolStripMenuItem; + private ToolStripMenuItem iceCreamToolStripMenuItem; + private ToolStripMenuItem ordersToolStripMenuItem; + private ToolStripMenuItem клиентыToolStripMenuItem; + private ToolStripMenuItem ImplementersToolStripMenuItem; + private ToolStripMenuItem DoWorkToolStripMenuItem; + private ToolStripMenuItem магазиныToolStripMenuItem; + private ToolStripMenuItem listShopsToolStripMenuItem; + private ToolStripMenuItem shopWorkloadToolStripMenuItem; + private ToolStripMenuItem ordersByDateToolStripMenuItem; + private ToolStripMenuItem MailToolStripMenuItem; private Button buttonSupplyShop; private Button SellIceCreamButton; - private ToolStripMenuItem listShopsToolStripMenuItem; - private ToolStripMenuItem shopWorkloadToolStripMenuItem; - private ToolStripMenuItem ordersByDateToolStripMenuItem; } -} \ No newline at end of file +} diff --git a/IceCreamShop/IceCreamShop/FormMain.cs b/IceCreamShop/IceCreamShop/FormMain.cs index 4d6f9f6..77bef3b 100644 --- a/IceCreamShop/IceCreamShop/FormMain.cs +++ b/IceCreamShop/IceCreamShop/FormMain.cs @@ -16,66 +16,75 @@ using System.Windows.Forms; namespace IceCreamShopView { - public partial class FormMain : Form - { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; + public partial class FormMain : Form + { + private readonly ILogger _logger; + private readonly IOrderLogic _orderLogic; + private readonly IReportLogic _reportLogic; private readonly IWorkProcess _workProcess; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; - _workProcess = workProcess; - } + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + _reportLogic = reportLogic; + _workProcess = workProcess; + } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } - private void LoadData() - { - _logger.LogInformation("Загрузка заказов"); - try - { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["IceCreamId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); + try + { + var list = _orderLogic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["IceCreamId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; + } + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void компонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } + private void компонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + if (service is FormComponents form) + { + form.ShowDialog(); + } + } - private void мороженоеToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormIceCreams)); - if (service is FormIceCreams form) - { - form.ShowDialog(); - } - } + private void мороженоеToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormIceCreams)); + if (service is FormIceCreams form) + { + form.ShowDialog(); + } + } + private void buttonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } + } private void магазиныToolStripMenuItem_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormShops)); @@ -85,76 +94,127 @@ namespace IceCreamShopView } } - private void buttonCreateOrder_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } - } + private void buttonSetToWork_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); + try + { + var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = id, + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка передачи заказа в работу"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } - private void buttonSetToFinish_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel - { - Id = id, - }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Заказ №{id} выдан", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + private void buttonSetToDone_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); + try + { + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel + { + Id = id, + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - private void buttonUpdate_Click(object sender, EventArgs e) - { - LoadData(); - } + private void buttonSetToFinish_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel + { + Id = id, + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + _logger.LogInformation("Заказ №{id} выдан", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - private void IceCreamsToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SaveIceCreamsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + private void buttonUpdate_Click(object sender, EventArgs e) + { + LoadData(); + } - private void IceCreamComponentsToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportProductComponents)); - if (service is FormReportProductComponents form) - { - form.ShowDialog(); - } - } + private void IceCreamsToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveIceCreamsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } - private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } - } + private void IceCreamComponentsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportProductComponents)); + if (service is FormReportProductComponents form) + { + form.ShowDialog(); + } + } + private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + if (service is FormReportOrders form) + { + form.ShowDialog(); + } + } + + private void клиентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormClients)); + if (service is FormClients form) + { + form.ShowDialog(); + } + } private void buttonSupplyShop_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormShopSupply)); @@ -205,30 +265,30 @@ namespace IceCreamShopView } } - private void клиентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } - } + private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); + if (service is FormImplementers form) + { + form.ShowDialog(); + } + } - private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); - if (service is FormImplementers form) - { - form.ShowDialog(); - } - } + private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork(( + Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + MessageBox.Show("Процесс обработки запущен", "Сообщение", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } - private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e) - { - _workProcess.DoWork(( - Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!,_orderLogic); - MessageBox.Show("Процесс обработки запущен", "Сообщение", - MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + private void MailToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormViewMail)); + if (service is FormViewMail form) + { + form.ShowDialog(); + } + } + } } diff --git a/IceCreamShop/IceCreamShop/FormMain.resx b/IceCreamShop/IceCreamShop/FormMain.resx index 81a9e3d..1319e7f 100644 --- a/IceCreamShop/IceCreamShop/FormMain.resx +++ b/IceCreamShop/IceCreamShop/FormMain.resx @@ -60,4 +60,7 @@ 17, 17 + + 53 + \ No newline at end of file diff --git a/IceCreamShop/IceCreamShop/FormReplyMail.Designer.cs b/IceCreamShop/IceCreamShop/FormReplyMail.Designer.cs new file mode 100644 index 0000000..03cbcff --- /dev/null +++ b/IceCreamShop/IceCreamShop/FormReplyMail.Designer.cs @@ -0,0 +1,149 @@ +namespace IceCreamShopView +{ + partial class FormReplyMail + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + textBoxReply = new TextBox(); + textBoxMainText = new TextBox(); + textBoxTitle = new TextBox(); + labelReply = new Label(); + labelMainText = new Label(); + labelTitle = new Label(); + buttonCancel = new Button(); + buttonSave = new Button(); + SuspendLayout(); + // + // textBoxReply + // + textBoxReply.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + textBoxReply.Location = new Point(137, 114); + textBoxReply.Multiline = true; + textBoxReply.Name = "textBoxReply"; + textBoxReply.Size = new Size(494, 182); + textBoxReply.TabIndex = 15; + // + // textBoxMainText + // + textBoxMainText.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + textBoxMainText.Location = new Point(137, 32); + textBoxMainText.Multiline = true; + textBoxMainText.Name = "textBoxMainText"; + textBoxMainText.ReadOnly = true; + textBoxMainText.Size = new Size(494, 76); + textBoxMainText.TabIndex = 14; + // + // textBoxTitle + // + textBoxTitle.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + textBoxTitle.Location = new Point(137, 2); + textBoxTitle.Name = "textBoxTitle"; + textBoxTitle.ReadOnly = true; + textBoxTitle.Size = new Size(494, 23); + textBoxTitle.TabIndex = 13; + // + // labelReply + // + labelReply.Location = new Point(14, 114); + labelReply.Name = "labelReply"; + labelReply.Size = new Size(117, 31); + labelReply.TabIndex = 12; + labelReply.Text = "Ответ на письмо:"; + labelReply.TextAlign = ContentAlignment.TopRight; + // + // labelMainText + // + labelMainText.Location = new Point(14, 35); + labelMainText.Name = "labelMainText"; + labelMainText.Size = new Size(117, 23); + labelMainText.TabIndex = 11; + labelMainText.Text = "Текст письма:"; + labelMainText.TextAlign = ContentAlignment.TopRight; + // + // labelTitle + // + labelTitle.Location = new Point(14, 6); + labelTitle.Name = "labelTitle"; + labelTitle.Size = new Size(117, 23); + labelTitle.TabIndex = 10; + labelTitle.Text = "Заголовок письма:"; + labelTitle.TextAlign = ContentAlignment.TopRight; + // + // buttonCancel + // + buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonCancel.Location = new Point(175, 302); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(117, 30); + buttonCancel.TabIndex = 9; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // buttonSave + // + buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonSave.Location = new Point(298, 302); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(117, 30); + buttonSave.TabIndex = 8; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // FormReplyMail + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(636, 344); + Controls.Add(textBoxReply); + Controls.Add(textBoxMainText); + Controls.Add(textBoxTitle); + Controls.Add(labelReply); + Controls.Add(labelMainText); + Controls.Add(labelTitle); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Name = "FormReplyMail"; + Text = "Ответ на письмо"; + Load += FormReplyMail_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private TextBox textBoxReply; + private TextBox textBoxMainText; + private TextBox textBoxTitle; + private Label labelReply; + private Label labelMainText; + private Label labelTitle; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShop/FormReplyMail.cs b/IceCreamShop/IceCreamShop/FormReplyMail.cs new file mode 100644 index 0000000..b27a968 --- /dev/null +++ b/IceCreamShop/IceCreamShop/FormReplyMail.cs @@ -0,0 +1,73 @@ +using IceCreamBusinessLogic.MailWorker; +using IceCreamShopContracts.BusinessLogicsContracts; +using IceCreamShopContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace IceCreamShopView +{ + public partial class FormReplyMail : Form + { + private readonly ILogger _logger; + private readonly AbstractMailWorker _mailWorker; + private readonly IMessageInfoLogic _logic; + private MessageInfoViewModel _message; + + public string MessageId { get; set; } = string.Empty; + + public FormReplyMail(ILogger 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 = _message.Subject, + Text = textBoxReply.Text, + }); + _logic.Update(new() + { + MessageId = MessageId, + Reply = textBoxReply.Text, + HasRead = true, + }); + MessageBox.Show("Успешно отправлено письмо", "Отправка письма", MessageBoxButtons.OK); + DialogResult = DialogResult.OK; + Close(); + } + + private void FormReplyMail_Load(object sender, EventArgs e) + { + try + { + _message = _logic.ReadElement(new() { MessageId = MessageId }); + if (_message == null) + throw new ArgumentNullException("Письма с таким id не существует"); + Text += $"для {_message.SenderName}"; + textBoxTitle.Text = _message.Subject; + textBoxMainText.Text = _message.Body; + if (_message.HasRead is false) + { + _logic.Update(new() { MessageId = MessageId, HasRead = true, Reply = _message.Reply }); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения собщения"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } +} diff --git a/IceCreamShop/IceCreamShop/FormReplyMail.resx b/IceCreamShop/IceCreamShop/FormReplyMail.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/IceCreamShop/IceCreamShop/FormReplyMail.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/IceCreamShop/IceCreamShop/FormViewMail.Designer.cs b/IceCreamShop/IceCreamShop/FormViewMail.Designer.cs new file mode 100644 index 0000000..87fe923 --- /dev/null +++ b/IceCreamShop/IceCreamShop/FormViewMail.Designer.cs @@ -0,0 +1,104 @@ +namespace IceCreamShopView +{ + partial class FormViewMail + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + labelInfoPages = new Label(); + buttonNextPage = new Button(); + buttonPrevPage = new Button(); + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // labelInfoPages + // + labelInfoPages.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + labelInfoPages.Location = new Point(99, 485); + labelInfoPages.Name = "labelInfoPages"; + labelInfoPages.Size = new Size(104, 19); + labelInfoPages.TabIndex = 7; + labelInfoPages.Text = "{0} страница"; + labelInfoPages.TextAlign = ContentAlignment.MiddleCenter; + // + // buttonNextPage + // + buttonNextPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonNextPage.Location = new Point(209, 481); + buttonNextPage.Name = "buttonNextPage"; + buttonNextPage.Size = new Size(75, 23); + buttonNextPage.TabIndex = 6; + buttonNextPage.Text = ">>>"; + buttonNextPage.UseVisualStyleBackColor = true; + buttonNextPage.Click += ButtonNextPage_Click; + // + // buttonPrevPage + // + buttonPrevPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonPrevPage.Location = new Point(18, 481); + buttonPrevPage.Name = "buttonPrevPage"; + buttonPrevPage.Size = new Size(75, 23); + buttonPrevPage.TabIndex = 5; + buttonPrevPage.Text = "<<<"; + buttonPrevPage.UseVisualStyleBackColor = true; + buttonPrevPage.Click += ButtonPrevPage_Click; + // + // dataGridView + // + dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(872, 463); + dataGridView.TabIndex = 4; + dataGridView.RowHeaderMouseClick += dataGridView_RowHeaderMouseClick; + // + // FormViewMail + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(896, 513); + Controls.Add(labelInfoPages); + Controls.Add(buttonNextPage); + Controls.Add(buttonPrevPage); + Controls.Add(dataGridView); + Name = "FormViewMail"; + Text = "Письма"; + Load += FormViewMail_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private Label labelInfoPages; + private Button buttonNextPage; + private Button buttonPrevPage; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShop/FormViewMail.cs b/IceCreamShop/IceCreamShop/FormViewMail.cs new file mode 100644 index 0000000..1fe9917 --- /dev/null +++ b/IceCreamShop/IceCreamShop/FormViewMail.cs @@ -0,0 +1,98 @@ +using IceCreamShop; +using IceCreamShopContracts.BusinessLogicsContracts; +using IceCreamShopContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace IceCreamShopView +{ + public partial class FormViewMail : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + private int currentPage = 1; + public int pageSize = 5; + + public FormViewMail(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + buttonPrevPage.Enabled = false; + } + + private void FormViewMail_Load(object sender, EventArgs e) + { + MailLoad(); + } + + private bool MailLoad() + { + try + { + var list = _logic.ReadList(new() + { + Page = currentPage, + PageSize = pageSize, + }); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка списка писем"); + labelInfoPages.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) + { + _logger.LogWarning("Неккоректный номер страницы {page}", currentPage - 1); + return; + } + currentPage--; + if (MailLoad()) + { + buttonNextPage.Enabled = true; + if (currentPage == 1) + buttonPrevPage.Enabled = false; + } + } + + private void ButtonNextPage_Click(object sender, EventArgs e) + { + currentPage++; + if (!MailLoad() || ((List)dataGridView.DataSource).Count == 0) + { + _logger.LogWarning("Out of range messages"); + currentPage--; + MailLoad(); + buttonNextPage.Enabled = false; + } + else + buttonPrevPage.Enabled = true; + } + + private void dataGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReplyMail)); + if (service is FormReplyMail form) + { + form.MessageId = (string)dataGridView.Rows[e.RowIndex].Cells["MessageId"].Value; + form.ShowDialog(); + MailLoad(); + } + } + } +} diff --git a/IceCreamShop/IceCreamShop/FormViewMail.resx b/IceCreamShop/IceCreamShop/FormViewMail.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/IceCreamShop/IceCreamShop/FormViewMail.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/IceCreamShop/IceCreamShop/IceCreamShopView.csproj b/IceCreamShop/IceCreamShop/IceCreamShopView.csproj index 318da33..05734e4 100644 --- a/IceCreamShop/IceCreamShop/IceCreamShopView.csproj +++ b/IceCreamShop/IceCreamShop/IceCreamShopView.csproj @@ -27,6 +27,9 @@ + + Always + Always diff --git a/IceCreamShop/IceCreamShop/Program.cs b/IceCreamShop/IceCreamShop/Program.cs index c8776a5..3eb361e 100644 --- a/IceCreamShop/IceCreamShop/Program.cs +++ b/IceCreamShop/IceCreamShop/Program.cs @@ -9,6 +9,8 @@ using IceCreamBusinessLogic.OfficePackage.Implements; using IceCreamBusinessLogic.OfficePackage; using IceCreamShopDatabaseImplement.Implements; using IceCreamBusinessLogic.BusinessLogic; +using IceCreamBusinessLogic.MailWorker; +using IceCreamShopContracts.BindingModels; namespace IceCreamShop { @@ -29,6 +31,28 @@ namespace IceCreamShop ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + + // + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } + Application.Run(_serviceProvider.GetRequiredService()); } @@ -44,7 +68,9 @@ namespace IceCreamShop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -53,6 +79,9 @@ namespace IceCreamShop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + + services.AddSingleton(); services.AddTransient(); services.AddTransient(); @@ -71,12 +100,17 @@ namespace IceCreamShop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + } + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + } } \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopClientApp/APIClient.cs b/IceCreamShop/IceCreamShopClientApp/APIClient.cs index 11828b7..f07b017 100644 --- a/IceCreamShop/IceCreamShopClientApp/APIClient.cs +++ b/IceCreamShop/IceCreamShopClientApp/APIClient.cs @@ -11,7 +11,9 @@ namespace IceCreamShopClientApp 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(); diff --git a/IceCreamShop/IceCreamShopClientApp/Controllers/HomeController.cs b/IceCreamShop/IceCreamShopClientApp/Controllers/HomeController.cs index be2cb9b..be9553f 100644 --- a/IceCreamShop/IceCreamShopClientApp/Controllers/HomeController.cs +++ b/IceCreamShop/IceCreamShopClientApp/Controllers/HomeController.cs @@ -3,6 +3,7 @@ using IceCreamShopContracts.ViewModels; using IceCreamShopClientApp.Models; using Microsoft.AspNetCore.Mvc; using System.Diagnostics; +using System.Text; namespace IceCreamShopClientApp.Controllers { @@ -143,5 +144,52 @@ namespace IceCreamShopClientApp.Controllers var prod = APIClient.GetRequest($"api/main/geticecream?icecreamId={icecream}"); return count * (prod?.Price ?? 1); } - } + + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(); + } + + [HttpGet] + public Tuple? SwitchPage(bool isNext) + { + if (isNext) + { + APIClient.CurrentPage++; + } + else + { + if (APIClient.CurrentPage == 1) + { + return null; + } + APIClient.CurrentPage--; + } + + var res = APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client!.Id}&page={APIClient.CurrentPage}"); + if (isNext && (res == null || res.Count == 0)) + { + APIClient.CurrentPage--; + return Tuple.Create(null, null, APIClient.CurrentPage != 1, false); + } + + StringBuilder htmlTable = new(); + foreach (var mail in res) + { + htmlTable.Append("" + + $"{mail.DateDelivery}" + + $"{mail.Subject}" + + $"{mail.Body}" + + "" + (mail.HasRead ? "Прочитано" : "Непрочитано") + "" + + $"{mail.Reply}" + + ""); + } + return Tuple.Create(htmlTable.ToString(), APIClient.CurrentPage.ToString(), APIClient.CurrentPage != 1, true); + } + } } \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopClientApp/Views/Home/Mails.cshtml b/IceCreamShop/IceCreamShopClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..5d3c058 --- /dev/null +++ b/IceCreamShop/IceCreamShopClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,81 @@ + +@{ + ViewData["Title"] = "Mails"; +} + +
+

Заказы

+
+ +
+ + + + + + + + + + + + +
+ Дата письма + + Заголовок + + Текст + + Статус + + Ответ +
+ +
+ + \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopClientApp/Views/Shared/_Layout.cshtml b/IceCreamShop/IceCreamShopClientApp/Views/Shared/_Layout.cshtml index 50d8b00..717e1d0 100644 --- a/IceCreamShop/IceCreamShopClientApp/Views/Shared/_Layout.cshtml +++ b/IceCreamShop/IceCreamShopClientApp/Views/Shared/_Layout.cshtml @@ -10,6 +10,7 @@ +
@@ -28,6 +29,9 @@ + diff --git a/IceCreamShop/IceCreamShopContracts/BindingModels/MailConfigBindingModel.cs b/IceCreamShop/IceCreamShopContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..26a6a2d --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,17 @@ +namespace IceCreamShopContracts.BindingModels +{ + public class MailConfigBindingModel + { + public string MailLogin { get; set; } = string.Empty; + + public string MailPassword { get; set; } = string.Empty; + + public string SmtpClientHost { get; set; } = string.Empty; + + public int SmtpClientPort { get; set; } + + public string PopHost { get; set; } = string.Empty; + + public int PopPort { get; set; } + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopContracts/BindingModels/MailSendInfoBindingModel.cs b/IceCreamShop/IceCreamShopContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..f09e154 --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,11 @@ +namespace IceCreamShopContracts.BindingModels +{ + public class MailSendInfoBindingModel + { + public string MailAddress { get; set; } = string.Empty; + + public string Subject { get; set; } = string.Empty; + + public string Text { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopContracts/BindingModels/MessageInfoBindingModel.cs b/IceCreamShop/IceCreamShopContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..f2a51d8 --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,23 @@ +using AbstractIceCreamShopDataModels.Models; + +namespace IceCreamShopContracts.BindingModels +{ + public class MessageInfoBindingModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + public string SenderName { get; set; } = string.Empty; + + public string Subject { get; set; } = string.Empty; + + public string Body { get; set; } = string.Empty; + + public DateTime DateDelivery { get; set; } + + public bool HasRead { get; set; } + + public string? Reply { get; set; } + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..ee3d45e --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.SearchModels; +using IceCreamShopContracts.ViewModels; + +namespace IceCreamShopContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + + bool Create(MessageInfoBindingModel model); + + bool Update(MessageInfoBindingModel model); + + MessageInfoViewModel? ReadElement(MessageInfoSearchModel model); + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopContracts/SearchModels/MessageInfoSearchModel.cs b/IceCreamShop/IceCreamShopContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..d05f11f --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,13 @@ +namespace IceCreamShopContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + + public string? MessageId { get; set; } + + public int? Page { get; set; } + + public int? PageSize { get; set; } + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopContracts/StoragesContracts/IMessageInfoStorage.cs b/IceCreamShop/IceCreamShopContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..97442f9 --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.SearchModels; +using IceCreamShopContracts.ViewModels; + +namespace IceCreamShopContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + + List GetFilteredList(MessageInfoSearchModel model); + + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + + MessageInfoViewModel? Update(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopContracts/ViewModels/MessageInfoViewModel.cs b/IceCreamShop/IceCreamShopContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..9c252bb --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,30 @@ +using AbstractIceCreamShopDataModels.Models; +using System.ComponentModel; + +namespace IceCreamShopContracts.ViewModels +{ + public class MessageInfoViewModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + [DisplayName("Отправитель")] + public string SenderName { get; set; } = string.Empty; + + [DisplayName("Дата письма")] + public DateTime DateDelivery { get; set; } + + [DisplayName("Заголовок")] + public string Subject { get; set; } = string.Empty; + + [DisplayName("Текст")] + public string Body { get; set; } = string.Empty; + + [DisplayName("Прочитано")] + public bool HasRead { get; set; } + + [DisplayName("Ответ")] + public string? Reply { get; set; } + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopDataModels/Models/IMessageInfoModel.cs b/IceCreamShop/IceCreamShopDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..bf97976 --- /dev/null +++ b/IceCreamShop/IceCreamShopDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,14 @@ +namespace AbstractIceCreamShopDataModels.Models +{ + public interface IMessageInfoModel + { + string MessageId { get; } + int? ClientId { get; } + string SenderName { get; } + DateTime DateDelivery { get; } + string Subject { get; } + string Body { get; } + public bool HasRead { get; } + public string? Reply { get; } + } +} diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/IceCreamShopDatabase.cs b/IceCreamShop/IceCreamShopDatabaseImplement/IceCreamShopDatabase.cs index fe7b6a3..725f80c 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/IceCreamShopDatabase.cs +++ b/IceCreamShop/IceCreamShopDatabaseImplement/IceCreamShopDatabase.cs @@ -26,6 +26,8 @@ namespace IceCreamShopDatabaseImplement public virtual DbSet Implementers { set; get; } + public virtual DbSet Messages { set; get; } + public virtual DbSet Shops { set; get; } public virtual DbSet ShopIcecreams { set; get; } } diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/IceCreamShopDatabaseImplement.csproj b/IceCreamShop/IceCreamShopDatabaseImplement/IceCreamShopDatabaseImplement.csproj index 616d02d..34c8218 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/IceCreamShopDatabaseImplement.csproj +++ b/IceCreamShop/IceCreamShopDatabaseImplement/IceCreamShopDatabaseImplement.csproj @@ -7,9 +7,9 @@ - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Implements/MessageInfoStorage.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..cbd80a1 --- /dev/null +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,68 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.SearchModels; +using IceCreamShopContracts.StoragesContracts; +using IceCreamShopContracts.ViewModels; +using IceCreamShopDatabaseImplement.Models; + +namespace IceCreamShopDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + using var context = new IceCreamShopDatabase(); + if (model.MessageId != null) + { + return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + using var context = new IceCreamShopDatabase(); + var res = context.Messages + .Where(x => !model.ClientId.HasValue || x.ClientId == model.ClientId) + .Select(x => x.GetViewModel); + if (!(model.Page.HasValue && model.PageSize.HasValue)) + { + return res.ToList(); + } + return res.Skip((model.Page.Value - 1) * model.PageSize.Value).Take(model.PageSize.Value).ToList(); + } + + public List GetFullList() + { + using var context = new IceCreamShopDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new IceCreamShopDatabase(); + var newMessage = MessageInfo.Create(model); + if (newMessage == null || context.Messages.Any(x => x.MessageId.Equals(model.MessageId))) + { + return null; + } + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + using var context = new IceCreamShopDatabase(); + var res = context.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId)); + if (res != null) + { + res.Update(model); + context.SaveChanges(); + } + return res?.GetViewModel; + } + } +} diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20230425055945_lab6_migr.Designer.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20230504152801_addsToMessage.Designer.cs similarity index 87% rename from IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20230425055945_lab6_migr.Designer.cs rename to IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20230504152801_addsToMessage.Designer.cs index 5405da0..1f8c13f 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20230425055945_lab6_migr.Designer.cs +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20230504152801_addsToMessage.Designer.cs @@ -12,15 +12,15 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace IceCreamShopDatabaseImplement.Migrations { [DbContext(typeof(IceCreamShopDatabase))] - [Migration("20230425055945_lab6_migr")] - partial class lab6_migr + [Migration("20230504152801_addsToMessage")] + partial class addsToMessage { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("ProductVersion", "7.0.5") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); @@ -143,6 +143,42 @@ namespace IceCreamShopDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("HasRead") + .HasColumnType("bit"); + + b.Property("Reply") + .HasColumnType("nvarchar(max)"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -263,6 +299,15 @@ namespace IceCreamShopDatabaseImplement.Migrations b.Navigation("IceCream"); }); + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("IceCreamShopDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Order", b => { b.HasOne("IceCreamShopDatabaseImplement.Models.Client", "Client") @@ -316,6 +361,8 @@ namespace IceCreamShopDatabaseImplement.Migrations modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Client", b => { + b.Navigation("Messages"); + b.Navigation("Orders"); }); diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20230425055945_lab6_migr.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20230504152801_addsToMessage.cs similarity index 87% rename from IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20230425055945_lab6_migr.cs rename to IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20230504152801_addsToMessage.cs index de0125b..afcc170 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20230425055945_lab6_migr.cs +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20230504152801_addsToMessage.cs @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations; namespace IceCreamShopDatabaseImplement.Migrations { /// - public partial class lab6_migr : Migration + public partial class addsToMessage : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) @@ -70,6 +70,29 @@ namespace IceCreamShopDatabaseImplement.Migrations table.PrimaryKey("PK_Implementers", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Messages", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: true), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false), + HasRead = table.Column(type: "bit", nullable: false), + Reply = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Messages", x => x.MessageId); + table.ForeignKey( + name: "FK_Messages_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + migrationBuilder.CreateTable( name: "IceCreamComponents", columns: table => new @@ -193,6 +216,11 @@ namespace IceCreamShopDatabaseImplement.Migrations table: "IceCreamComponents", column: "IceCreamId"); + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + migrationBuilder.CreateIndex( name: "IX_Orders_ClientId", table: "Orders", @@ -230,6 +258,9 @@ namespace IceCreamShopDatabaseImplement.Migrations migrationBuilder.DropTable( name: "IceCreamComponents"); + migrationBuilder.DropTable( + name: "Messages"); + migrationBuilder.DropTable( name: "Orders"); diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/IceCreamShopDatabaseModelSnapshot.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/IceCreamShopDatabaseModelSnapshot.cs index 3bfc56d..694ada9 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/IceCreamShopDatabaseModelSnapshot.cs +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/IceCreamShopDatabaseModelSnapshot.cs @@ -17,7 +17,7 @@ namespace IceCreamShopDatabaseImplement.Migrations { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("ProductVersion", "7.0.5") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); @@ -140,6 +140,42 @@ namespace IceCreamShopDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("HasRead") + .HasColumnType("bit"); + + b.Property("Reply") + .HasColumnType("nvarchar(max)"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -260,6 +296,15 @@ namespace IceCreamShopDatabaseImplement.Migrations b.Navigation("IceCream"); }); + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("IceCreamShopDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Order", b => { b.HasOne("IceCreamShopDatabaseImplement.Models.Client", "Client") @@ -281,6 +326,8 @@ namespace IceCreamShopDatabaseImplement.Migrations b.Navigation("Client"); b.Navigation("IceCream"); + + b.Navigation("Implementer"); }); modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.ShopIcecream", b => @@ -304,6 +351,8 @@ namespace IceCreamShopDatabaseImplement.Migrations modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Client", b => { + b.Navigation("Messages"); + b.Navigation("Orders"); }); diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Models/Client.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Models/Client.cs index 6bdc89d..d581f9d 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/Models/Client.cs +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Models/Client.cs @@ -22,7 +22,10 @@ namespace IceCreamShopDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); - public static Client? Create(ClientBindingModel model) + [ForeignKey("ClientId")] + public virtual List Messages { get; set; } = new(); + + public static Client? Create(ClientBindingModel model) { if (model == null) { diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Models/MessageInfo.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..c88ff01 --- /dev/null +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,70 @@ +using AbstractIceCreamShopDataModels.Models; +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.ViewModels; +using System.ComponentModel.DataAnnotations; + +namespace IceCreamShopDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public Client? Client { get; private set; } + + public bool HasRead { get; private set; } + + public string? Reply { get; private set; } + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Reply = model.Reply, + HasRead = model.HasRead, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + Reply = model.Reply; + HasRead = model.HasRead; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Reply = Reply, + HasRead = HasRead, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/IceCreamShop/IceCreamShopFileImplement/DataFileSingleton.cs b/IceCreamShop/IceCreamShopFileImplement/DataFileSingleton.cs index cf0e0b5..5da1811 100644 --- a/IceCreamShop/IceCreamShopFileImplement/DataFileSingleton.cs +++ b/IceCreamShop/IceCreamShopFileImplement/DataFileSingleton.cs @@ -11,12 +11,14 @@ namespace IceCreamShopFileImplement private readonly string IceCreamFileName = "IceCream.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageInfoFileName = "MessageInfo.xml"; private readonly string ShopFileName = "Shop.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List IceCreams { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } + public List Messages { get; private set; } public List Shops { get; private set; } public static DataFileSingleton GetInstance() { @@ -31,6 +33,7 @@ namespace IceCreamShopFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement); public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); private DataFileSingleton() { @@ -39,6 +42,7 @@ namespace IceCreamShopFileImplement Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/IceCreamShop/IceCreamShopFileImplement/Implements/MessageInfoStorage.cs b/IceCreamShop/IceCreamShopFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..72b4fe0 --- /dev/null +++ b/IceCreamShop/IceCreamShopFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,68 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.SearchModels; +using IceCreamShopContracts.StoragesContracts; +using IceCreamShopContracts.ViewModels; +using IceCreamShopFileImplement.Models; + +namespace IceCreamShopFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton _source; + public MessageInfoStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId != null) + { + return _source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + var res = _source.Messages + .Where(x => !model.ClientId.HasValue || x.ClientId == model.ClientId) + .Select(x => x.GetViewModel); + if (!(model.Page.HasValue && model.PageSize.HasValue)) + { + return res.ToList(); + } + return res.Skip((model.Page.Value - 1) * model.PageSize.Value).Take(model.PageSize.Value).ToList(); + } + + public List GetFullList() + { + return _source.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + _source.SaveMessages(); + return newMessage.GetViewModel; + } + + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + var res = _source.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId)); + if (res != null) + { + res.Update(model); + _source.SaveMessages(); + } + return res?.GetViewModel; + } + } +} diff --git a/IceCreamShop/IceCreamShopFileImplement/Models/MessageInfo.cs b/IceCreamShop/IceCreamShopFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..d72f0b1 --- /dev/null +++ b/IceCreamShop/IceCreamShopFileImplement/Models/MessageInfo.cs @@ -0,0 +1,97 @@ +using AbstractIceCreamShopDataModels.Models; +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.ViewModels; +using System.Xml.Linq; + +namespace IceCreamShopFileImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public bool HasRead { get; private set; } + + public string? Reply { get; private set; } + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Reply = model.Reply, + HasRead = model.HasRead, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public static MessageInfo? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Reply = element.Attribute("Reply")!.Value, + HasRead = Convert.ToBoolean(element.Attribute("HasRead")!.Value), + Subject = element.Attribute("Subject")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + SenderName = element.Attribute("SenderName")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + }; + } + + public void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + Reply = model.Reply; + HasRead = model.HasRead; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Reply = Reply, + HasRead = HasRead, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Body", Body), + new XAttribute("Reply", Reply), + new XAttribute("HasRead", HasRead), + new XAttribute("Subject", Subject), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/IceCreamShop/IceCreamShopListImplement/DataListSingleton.cs b/IceCreamShop/IceCreamShopListImplement/DataListSingleton.cs index e0e0262..552f47d 100644 --- a/IceCreamShop/IceCreamShopListImplement/DataListSingleton.cs +++ b/IceCreamShop/IceCreamShopListImplement/DataListSingleton.cs @@ -10,6 +10,7 @@ namespace IceCreamShopListImplement public List iceCreams { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } public List Shops { get; set; } private DataListSingleton() @@ -19,6 +20,7 @@ namespace IceCreamShopListImplement iceCreams = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); Shops = new List(); } public static DataListSingleton GetInstance() diff --git a/IceCreamShop/IceCreamShopListImplement/Implements/MessageInfoStorage.cs b/IceCreamShop/IceCreamShopListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..7332916 --- /dev/null +++ b/IceCreamShop/IceCreamShopListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,88 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.SearchModels; +using IceCreamShopContracts.StoragesContracts; +using IceCreamShopContracts.ViewModels; +using IceCreamShopListImplement.Models; + +namespace IceCreamShopListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + foreach (var message in _source.Messages) + { + if (model.MessageId != null && model.MessageId.Equals(message.MessageId)) + return message.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + List result = new(); + foreach (var item in _source.Messages) + { + if (item.ClientId.HasValue && item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + + if (!(model.Page.HasValue && model.PageSize.HasValue)) + { + return result; + } + if (model.Page * model.PageSize >= result.Count) + { + return null; + } + List filteredResult = new(); + for (var i = (model.Page.Value - 1) * model.PageSize.Value; i < model.Page.Value * model.PageSize.Value; i++) + { + filteredResult.Add(result[i]); + } + return filteredResult; + } + + public List GetFullList() + { + List result = new(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _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; + } + } +} diff --git a/IceCreamShop/IceCreamShopListImplement/Models/MessageInfo.cs b/IceCreamShop/IceCreamShopListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..e510a2f --- /dev/null +++ b/IceCreamShop/IceCreamShopListImplement/Models/MessageInfo.cs @@ -0,0 +1,66 @@ +using AbstractIceCreamShopDataModels.Models; +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.ViewModels; + +namespace IceCreamShopListImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public bool HasRead { get; private set; } + + public string? Reply { get; private set; } + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Reply = model.Reply, + HasRead = model.HasRead, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + Reply = model.Reply; + HasRead = model.HasRead; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Reply = Reply, + HasRead = HasRead, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/IceCreamShop/IceCreamShopRestApi/Controllers/ClientController.cs b/IceCreamShop/IceCreamShopRestApi/Controllers/ClientController.cs index a1a7b8a..3e60c42 100644 --- a/IceCreamShop/IceCreamShopRestApi/Controllers/ClientController.cs +++ b/IceCreamShop/IceCreamShopRestApi/Controllers/ClientController.cs @@ -14,10 +14,15 @@ namespace IceCreamShopRestApi.Controllers private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger logger) + private readonly IMessageInfoLogic _mailLogic; + + public int pageSize = 4; + + public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger logger) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } [HttpGet] @@ -65,5 +70,24 @@ namespace IceCreamShopRestApi.Controllers throw; } } + + [HttpGet] + public List? GetMessages(int clientId, int page) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId, + Page = page, + PageSize = pageSize + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } } } \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopRestApi/Order.xml b/IceCreamShop/IceCreamShopRestApi/Order.xml new file mode 100644 index 0000000..58e6d39 --- /dev/null +++ b/IceCreamShop/IceCreamShopRestApi/Order.xml @@ -0,0 +1,8 @@ + + + + user + icecreamshop2023tp@gmail.com + user + + \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopRestApi/Program.cs b/IceCreamShop/IceCreamShopRestApi/Program.cs index b759206..d2674b5 100644 --- a/IceCreamShop/IceCreamShopRestApi/Program.cs +++ b/IceCreamShop/IceCreamShopRestApi/Program.cs @@ -1,4 +1,6 @@ using IceCreamBusinessLogic.BusinessLogics; +using IceCreamBusinessLogic.MailWorker; +using IceCreamShopContracts.BindingModels; using IceCreamShopContracts.BusinessLogicsContracts; using IceCreamShopContracts.StoragesContracts; using IceCreamShopDatabaseImplement.Implements; @@ -14,14 +16,18 @@ builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddSingleton(); + builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); @@ -32,6 +38,17 @@ builder.Services.AddSwaggerGen(c => var app = builder.Build(); +var mailSender = app.Services.GetService(); +mailSender?.MailConfig(new MailConfigBindingModel +{ + MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty, + MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty, + SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty, + SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()), + PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty, + PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString()) +}); + // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { diff --git a/IceCreamShop/IceCreamShopRestApi/appsettings.json b/IceCreamShop/IceCreamShopRestApi/appsettings.json index 10f68b8..48d6a5e 100644 --- a/IceCreamShop/IceCreamShopRestApi/appsettings.json +++ b/IceCreamShop/IceCreamShopRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "icecreamshop2023tp@gmail.com", + "MailPassword": "czts meyw wpbg miiv" }