Compare commits

...

2 Commits

Author SHA1 Message Date
719dae666f idk 2024-04-28 10:33:11 +04:00
d080e573ce Autification failed надо исправлять 2024-04-28 09:02:29 +04:00
45 changed files with 1475 additions and 255 deletions

View File

@ -8,6 +8,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CarpentryWorkshopBusinessLogic.BusinessLogics
@ -16,11 +17,13 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IClientStorage _clientStorage;
public ClientLogic(ILogger<ClientLogic> logger, IClientStorage clientStorage)
{
_logger = logger;
_clientStorage = clientStorage;
}
public bool Create(ClientBindingModel model)
{
CheckModel(model);
@ -50,7 +53,7 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ClientFIO:{ClientFIO}. Id:{ Id}", model.ClientFIO, model.Id);
_logger.LogInformation("ReadElement. ClientFIO:{ClientFIO}. Email: {Email}. Id:{ Id}", model.ClientFIO, model.Email, model.Id);
var element = _clientStorage.GetElement(model);
if (element == null)
{
@ -63,7 +66,7 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
public List<ClientViewModel>? ReadList(ClientSearchModel? model)
{
_logger.LogInformation("ReadList. ClientFIO:{ClientFIO}. Id:{Id}", model?.ClientFIO, model?.Id);
_logger.LogInformation("ReadList. ClientId:{Id}", model?.Id);
var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model);
if (list == null)
{
@ -84,6 +87,7 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
}
return true;
}
private void CheckModel(ClientBindingModel model, bool withParams = true)
{
if (model == null)
@ -96,24 +100,32 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
}
if (string.IsNullOrEmpty(model.ClientFIO))
{
throw new ArgumentNullException("Нет ФИО клиента", nameof(model.ClientFIO));
throw new ArgumentNullException("Нет ФИО пользователя", nameof(model.ClientFIO));
}
if (string.IsNullOrEmpty(model.Email))
{
throw new ArgumentNullException("У клиента отсутствует почта", nameof(model.Email));
throw new ArgumentNullException("Нет почты клиента", nameof(model.Email));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("У клиента отсутствует пароль", nameof(model.Email));
throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password));
}
_logger.LogInformation("Client. ClientID:{Id}. ClientFIO: {ClientFIO}. Email:{ Email}. Password: { Password}", model.Id, model.ClientFIO, model.Email, model.Password);
if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase))
{
throw new ArgumentException("Неправильно введенный email", nameof(model.Email));
}
if (!Regex.IsMatch(model.Password, @"^^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$", RegexOptions.IgnoreCase) || model.Password.Length < 3 || model.Password.Length > 50)
{
throw new ArgumentException("Неправильно введенный пароль", nameof(model.Password));
}
_logger.LogInformation("Client. ClientFIO:{ClientFIO}.Email:{Email}.Id:{Id}", model.ClientFIO, model.Email, model.Id);
var element = _clientStorage.GetElement(new ClientSearchModel
{
Email = model.Email
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Такой клиент уже существует");
throw new InvalidOperationException("Клиент с таким именем уже есть");
}
}
}

View File

@ -0,0 +1,65 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopBusinessLogic.BusinessLogics
{
public class MessageInfoLogic : IMessageInfoLogic
{
private readonly ILogger _logger;
private readonly IMessageInfoStorage _messageInfoStorage;
public MessageInfoLogic(ILogger<MessageInfoLogic> logger, IMessageInfoStorage messageInfoStorage)
{
_logger = logger;
_messageInfoStorage = messageInfoStorage;
}
public bool Create(MessageInfoBindingModel model)
{
var element = _messageInfoStorage.GetElement(new MessageInfoSearchModel
{
MessageId = model.MessageId
});
if (element != null)
{
if (_messageInfoStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
else
{
if (_messageInfoStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
}
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
{
_logger.LogInformation("ReadList. ClientId:{ClientId}", 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;
}
}
}

View File

@ -1,4 +1,5 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopBusinessLogic.MailWorker;
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
@ -7,9 +8,11 @@ using CarpentryWorkshopDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace CarpentryWorkshopBusinessLogic.BusinessLogics
{
@ -17,11 +20,15 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly AbstractMailWorker _mailWorker;
private readonly IClientLogic _clientLogic;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic)
{
_logger = logger;
_orderStorage = orderStorage;
_mailWorker = mailWorker;
_clientLogic = clientLogic;
}
public bool CreateOrder(OrderBindingModel model)
@ -35,14 +42,17 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
}
model.Status = OrderStatus.Принят;
var result = _orderStorage.Insert(model);
if (_orderStorage.Insert(model) == null)
if (result == null)
{
model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Insert operation failed");
return false;
}
SendOrderMessage(result.ClientId, $"Установка ПО, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят");
return true;
}
@ -76,13 +86,36 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
model.Sum = vmodel.Sum;
model.Count = vmodel.Count;
if (_orderStorage.Update(model) == null)
var result = _orderStorage.Update(model);
if (result == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
SendOrderMessage(result.ClientId, $"Установка ПО, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}");
return true;
}
private bool SendOrderMessage(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;
}
@ -93,7 +126,7 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
public bool DeliveryOrder(OrderBindingModel model)
{
model.DateImplement = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
model.DateImplement = DateTime.Now;
return StatusUpdate(model, OrderStatus.Готов);
}
@ -118,26 +151,29 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
return list;
}
private bool CheckModel(OrderBindingModel model)
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.WoodId < 0)
{
throw new ArgumentNullException("Некорректный идентификатор у изделия", nameof(model.WoodId));
}
if (model.Count <= 0)
{
throw new ArgumentException("Количество изделий в заказе должно быть больше 0", nameof(model.Count));
throw new ArgumentNullException("Количество изделий в заказе должно быть больше 0", nameof(model.Count));
}
if (model.Sum <= 0)
{
throw new ArgumentException("Суммарная стоимость заказа должна быть больше 0", nameof(model.Sum));
throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
}
if (model.DateCreate > model.DateImplement)
{
throw new ArgumentException("Время создания заказа не может быть больше времени его выполнения", nameof(model.DateImplement));
}
return true;
_logger.LogInformation("Order. OrderID:{Id}. Sum:{ Sum}. WoodId: { WoodId}", model.Id, model.Sum, model.WoodId);
}
public OrderViewModel? ReadElement(OrderSearchModel model)

View File

@ -8,6 +8,7 @@
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.19.0" />
<PackageReference Include="MailKit" Version="4.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="PDFsharp-MigraDoc" Version="1.50.5147" />
</ItemGroup>

View File

@ -0,0 +1,68 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace CarpentryWorkshopBusinessLogic.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 IMessageInfoLogic _messageInfoLogic;
public AbstractMailWorker(IMessageInfoLogic messageInfoLogic)
{
_messageInfoLogic = messageInfoLogic;
}
public void MailConfig(MailConfigBindingModel config)
{
_mailLogin = config.MailLogin;
_mailPassword = config.MailPassword;
_smtpClientHost = config.SmtpClientHost;
_smtpClientPort = config.SmtpClientPort;
_popHost = config.PopHost;
_popPort = config.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;
}
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();
foreach (var mail in list)
{
_messageInfoLogic.Create(mail);
}
}
protected abstract Task SendMailAsync(MailSendInfoBindingModel info);
protected abstract Task<List<MessageInfoBindingModel>> ReceiveMailAsync();
}
}

View File

@ -0,0 +1,82 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using MailKit.Net.Pop3;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Mail;
using System.Text;
namespace CarpentryWorkshopBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
private IClientStorage _clientStorage;
public MailKitWorker(IMessageInfoLogic messageInfoLogic, IClientStorage clientStorage) : base(messageInfoLogic)
{
_clientStorage = clientStorage;
}
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<List<MessageInfoBindingModel>> ReceiveMailAsync()
{
var list = new List<MessageInfoBindingModel>();
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
{
ClientId = _clientStorage.GetElement(new ClientSearchModel { Email = mail.Address })?.Id,
DateDelivery = message.Date.DateTime,
MessageId = message.MessageId,
SenderName = mail.Address,
Subject = message.Subject,
Body = message.TextBody
});
}
}
}
catch (MailKit.Security.AuthenticationException)
{ }
finally
{
client.Disconnect(true);
}
});
return list;
}
}
}

View File

@ -149,5 +149,14 @@ namespace CarpentryWorkshopClientApp.Controllers
var prod = APIClient.GetRequest<WoodViewModel>($"api/main/getwood?woodId={wood}");
return count * (prod?.Price ?? 1);
}
[HttpGet]
public IActionResult Mails()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<MessageInfoViewModel>>($"api/client/getmessages?clientId={APIClient.Client.Id}"));
}
}
}

View File

@ -0,0 +1,54 @@
@using CarpentryWorkshopContracts.ViewModels
@model List<MessageInfoViewModel>
@{
ViewData["Title"] = "Mails";
}
<div class="text-center">
<h1 class="display-4">Заказы</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<table class="table">
<thead>
<tr>
<th>
Дата письма
</th>
<th>
Заголовок
</th>
<th>
Текст
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DateDelivery)
</td>
<td>
@Html.DisplayFor(modelItem => item.Subject)
</td>
<td>
@Html.DisplayFor(modelItem => item.Body)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -28,6 +28,9 @@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Mails">Письма</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Enter">Вход</a>
</li>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.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; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.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;
}
}

View File

@ -0,0 +1,19 @@
using CarpentryWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.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; }
}
}

View File

@ -0,0 +1,13 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.ViewModels;
namespace CarpentryWorkshopContracts.BusinessLogicsContracts
{
public interface IMessageInfoLogic
{
List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model);
bool Create(MessageInfoBindingModel model);
}
}

View File

@ -0,0 +1,9 @@
namespace CarpentryWorkshopContracts.SearchModels
{
public class MessageInfoSearchModel
{
public int? ClientId { get; set; }
public string? MessageId { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.ViewModels;
namespace CarpentryWorkshopContracts.StoragesContracts
{
public interface IMessageInfoStorage
{
List<MessageInfoViewModel> GetFullList();
List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model);
MessageInfoViewModel? GetElement(MessageInfoSearchModel model);
MessageInfoViewModel? Insert(MessageInfoBindingModel model);
MessageInfoViewModel? Update(MessageInfoBindingModel model);
}
}

View File

@ -0,0 +1,24 @@
using CarpentryWorkshopDataModels.Models;
using System.ComponentModel;
namespace CarpentryWorkshopContracts.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;
}
}

View File

@ -0,0 +1,12 @@
namespace CarpentryWorkshopDataModels.Models
{
public interface IMessageInfoModel
{
string MessageId { get; }
int? ClientId { get; }
string SenderName { get; }
DateTime DateDelivery { get; }
string Subject { get; }
string Body { get; }
}
}

View File

@ -24,5 +24,6 @@ namespace CarpentryWorkshopDatabaseImplement
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
public virtual DbSet<MessageInfo> MessageInfos { set; get; }
}
}

View File

@ -16,50 +16,37 @@ namespace CarpentryWorkshopDatabaseImplement.Implements
public ClientViewModel? Delete(ClientBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var res = context.Clients.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
var element = context.Clients.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Clients.Remove(res);
context.Clients.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return res?.GetViewModel;
return null;
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
if (string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password) && !model.Id.HasValue)
{
return null;
}
using var context = new CarpentryWorkshopDatabase();
if (model.Id.HasValue)
return context.Clients.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.Email != null && model.Password != null)
return context.Clients
.FirstOrDefault(x => x.Email.Equals(model.Email)
&& x.Password.Equals(model.Password))
?.GetViewModel;
if (model.Email != null)
return context.Clients.FirstOrDefault(x => x.Email.Equals(model.Email))?.GetViewModel;
return null;
return context.Clients.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) ||
(!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO == model.ClientFIO) ||
(!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password)))?.GetViewModel;
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
if (model == null)
if (string.IsNullOrEmpty(model.ClientFIO))
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.Email != null)
{
using var context = new CarpentryWorkshopDatabase();
return context.Clients
.Where(x => x.Email.Contains(model.Email))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
using var context = new CarpentryWorkshopDatabase();
return context.Clients.Where(x => x.ClientFIO.Contains(model.ClientFIO)).Select(x => x.GetViewModel).ToList();
}
public List<ClientViewModel> GetFullList()
@ -70,23 +57,28 @@ namespace CarpentryWorkshopDatabaseImplement.Implements
public ClientViewModel? Insert(ClientBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var res = Client.Create(model);
if (res != null)
var newComponent = Client.Create(model);
if (newComponent == null)
{
context.Clients.Add(res);
context.SaveChanges();
return null;
}
return res?.GetViewModel;
using var context = new CarpentryWorkshopDatabase();
context.Clients.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ClientViewModel? Update(ClientBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var res = context.Clients.FirstOrDefault(x => x.Id == model.Id);
res?.Update(model);
var component = context.Clients.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return res?.GetViewModel;
return component.GetViewModel;
}
}
}

View File

@ -0,0 +1,64 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
public List<MessageInfoViewModel> GetFullList()
{
using var context = new CarpentryWorkshopDatabase();
return context.MessageInfos.Select(x => x.GetViewModel).ToList();
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
if (!model.ClientId.HasValue)
{
return new();
}
using var context = new CarpentryWorkshopDatabase();
return context.MessageInfos.Where(x => x.ClientId.HasValue && x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (string.IsNullOrEmpty(model.MessageId))
{
return new();
}
using var context = new CarpentryWorkshopDatabase();
return context.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel;
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
var newMessage = MessageInfo.Create(model);
if (newMessage == null)
{
return null;
}
using var context = new CarpentryWorkshopDatabase();
context.MessageInfos.Add(newMessage);
context.SaveChanges();
return newMessage.GetViewModel;
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var component = context.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
}
}

View File

@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace CarpentryWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(CarpentryWorkshopDatabase))]
[Migration("20240427190111_InitialCreate")]
[Migration("20240428043913_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
@ -97,6 +97,36 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.ToTable("Implementers");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("text");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ClientId")
.HasColumnType("integer");
b.Property<DateTime>("DateDelivery")
.HasColumnType("timestamp with time zone");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("text");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("MessageInfos");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -186,10 +216,19 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.ToTable("WoodComponents");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("ClientMessages")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.WithMany("ClientOrders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
@ -232,7 +271,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Client", b =>
{
b.Navigation("Orders");
b.Navigation("ClientMessages");
b.Navigation("ClientOrders");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Component", b =>

View File

@ -71,6 +71,27 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
table.PrimaryKey("PK_Woods", x => x.Id);
});
migrationBuilder.CreateTable(
name: "MessageInfos",
columns: table => new
{
MessageId = table.Column<string>(type: "text", nullable: false),
ClientId = table.Column<int>(type: "integer", nullable: true),
SenderName = table.Column<string>(type: "text", nullable: false),
DateDelivery = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
Subject = table.Column<string>(type: "text", nullable: false),
Body = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_MessageInfos", x => x.MessageId);
table.ForeignKey(
name: "FK_MessageInfos_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
@ -135,6 +156,11 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_MessageInfos_ClientId",
table: "MessageInfos",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ClientId",
table: "Orders",
@ -164,6 +190,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "MessageInfos");
migrationBuilder.DropTable(
name: "Orders");

View File

@ -94,6 +94,36 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.ToTable("Implementers");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("text");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ClientId")
.HasColumnType("integer");
b.Property<DateTime>("DateDelivery")
.HasColumnType("timestamp with time zone");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("text");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("MessageInfos");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -183,10 +213,19 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.ToTable("WoodComponents");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("ClientMessages")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.WithMany("ClientOrders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
@ -229,7 +268,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Client", b =>
{
b.Navigation("Orders");
b.Navigation("ClientMessages");
b.Navigation("ClientOrders");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Component", b =>

View File

@ -8,14 +8,13 @@ using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CarpentryWorkshopDatabaseImplement.Models;
namespace CarpentryWorkshopDatabaseImplement.Models
{
public class Client : IClientModel
{
public int Id { get; set; }
[Required]
public string ClientFIO { get; set; } = string.Empty;
@ -25,43 +24,36 @@ namespace CarpentryWorkshopDatabaseImplement.Models
[Required]
public string Password { get; set; } = string.Empty;
public int Id { get; set; }
[ForeignKey("ClientId")]
public virtual List<Order> ClientOrders { get; set; } = new();
[ForeignKey("ClientId")]
public virtual List<Order> Orders { get; set; } = new();
public static Client? Create(ClientBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Id = model.Id,
ClientFIO = model.ClientFIO,
Email = model.Email,
Password = model.Password
};
}
public void Update(ClientBindingModel model)
{
if (model == null)
{
return;
}
ClientFIO = model.ClientFIO;
Email = model.Email;
Password = model.Password;
}
public virtual List<MessageInfo> ClientMessages { get; set; } = new();
public ClientViewModel GetViewModel => new()
{
Id = Id,
ClientFIO = ClientFIO,
Email = Email,
Password = Password,
Password = Password
};
public static Client Create(ClientBindingModel model)
{
return new Client()
{
Id = model.Id,
ClientFIO = model.ClientFIO,
Email = model.Email,
Password = model.Password,
};
}
public void Update(ClientBindingModel model)
{
ClientFIO = model.ClientFIO;
Email = model.Email;
Password = model.Password;
}
}
}

View File

@ -0,0 +1,67 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement.Models
{
public class MessageInfo : IMessageInfoModel
{
[Key]
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
public virtual Client? Client { get; set; }
public string SenderName { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; }
public string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public static MessageInfo? Create(MessageInfoBindingModel? model)
{
if (model == null)
{
return null;
}
return new()
{
MessageId = model.MessageId,
ClientId = model.ClientId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
Subject = model.Subject,
Body = model.Body,
};
}
public void Update(MessageInfoBindingModel model)
{
MessageId = model.MessageId;
ClientId = model.ClientId;
SenderName = model.SenderName;
DateDelivery = model.DateDelivery;
Subject = model.Subject;
Body = model.Body;
}
public MessageInfoViewModel GetViewModel => new()
{
MessageId = MessageId,
ClientId = ClientId,
SenderName = SenderName,
DateDelivery = DateDelivery,
Subject = Subject,
Body = Body
};
}
}

View File

@ -11,6 +11,8 @@ namespace CarpentryWorkshopFileImplement
private readonly string WoodFileName = "Wood.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
private readonly string MessageFileName = "Message.xml";
public List<Message> Messages { get; private set; }
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Wood> Woods { get; private set; }
@ -28,6 +30,7 @@ namespace CarpentryWorkshopFileImplement
public void SaveWoods() => SaveData(Woods, WoodFileName, "Woods", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
private DataFileSingleton()
@ -37,6 +40,7 @@ namespace CarpentryWorkshopFileImplement
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(MessageFileName, "Message", x => Message.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{

View File

@ -13,84 +13,81 @@ namespace CarpentryWorkshopFileImplement.Implements
{
public class ClientStorage : IClientStorage
{
private readonly DataFileSingleton _source;
private readonly DataFileSingleton source;
public ClientStorage()
{
_source = DataFileSingleton.GetInstance();
}
public ClientViewModel? Delete(ClientBindingModel model)
{
var res = _source.Clients.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
_source.Clients.Remove(res);
_source.SaveClients();
}
return res?.GetViewModel;
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
if (model.Id.HasValue)
return _source.Clients.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.Email != null && model.Password != null)
return _source.Clients
.FirstOrDefault(x => x.Email.Equals(model.Email)
&& x.Password.Equals(model.Password))
?.GetViewModel;
if (model.Email != null)
return _source.Clients.FirstOrDefault(x => x.Email.Equals(model.Email))?.GetViewModel;
return null;
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
if (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.Email != null)
{
return _source.Clients
.Where(x => x.Email.Contains(model.Email))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
source = DataFileSingleton.GetInstance();
}
public List<ClientViewModel> GetFullList()
{
return _source.Clients.Select(x => x.GetViewModel).ToList();
return source.Clients
.Select(x => x.GetViewModel)
.ToList();
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
if (string.IsNullOrEmpty(model.ClientFIO) && string.IsNullOrEmpty(model.Email))
{
return new();
}
return source.Clients
.Where(x => (!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO.Contains(model.ClientFIO)) ||
(!string.IsNullOrEmpty(model.Email) && x.ClientFIO.Contains(model.Email)))
.Select(x => x.GetViewModel)
.ToList();
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
if (!model.Id.HasValue && string.IsNullOrEmpty(model.ClientFIO) && string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password))
{
return null;
}
return source.Clients
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) ||
(!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO == model.ClientFIO) ||
(!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Password) && x.Email == model.Email && x.Password == model.Password))
?.GetViewModel;
}
public ClientViewModel? Insert(ClientBindingModel model)
{
model.Id = _source.Clients.Count > 0 ? _source.Clients.Max(x => x.Id) + 1 : 1;
var res = Client.Create(model);
if (res != null)
model.Id = source.Components.Count > 0 ? source.Components.Max(x => x.Id) + 1 : 1;
var newClient = Client.Create(model);
if (newClient == null)
{
_source.Clients.Add(res);
_source.SaveClients();
return null;
}
return res?.GetViewModel;
source.Clients.Add(newClient);
source.SaveClients();
return newClient.GetViewModel;
}
public ClientViewModel? Update(ClientBindingModel model)
{
var res = _source.Clients.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
var client = source.Clients.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
res.Update(model);
_source.SaveClients();
return null;
}
return res?.GetViewModel;
client.Update(model);
source.SaveClients();
return client.GetViewModel;
}
public ClientViewModel? Delete(ClientBindingModel model)
{
var element = source.Clients.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Clients.Remove(element);
source.SaveClients();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,66 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopFileImplement.Models;
namespace CarpentryWorkshopFileImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
private readonly DataFileSingleton source;
public MessageInfoStorage()
{
source = DataFileSingleton.GetInstance();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (model.MessageId == null)
return null;
return source.Messages.FirstOrDefault(x =>
x.MessageId == model.MessageId)?.GetViewModel;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
if (!model.ClientId.HasValue)
{
return new();
}
return source.Messages
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
public List<MessageInfoViewModel> GetFullList()
{
return source.Messages
.Select(x => x.GetViewModel)
.ToList();
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
var newMessage = Message.Create(model);
if (newMessage == null)
{
return null;
}
source.Messages.Add(newMessage);
source.SaveMessages();
return newMessage.GetViewModel;
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
var component = source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId);
if (component == null)
{
return null;
}
component.Update(model);
source.SaveMessages();
return component.GetViewModel;
}
}
}

View File

@ -8,18 +8,14 @@ using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace CarpentryWorkshopFileImplement.Models
{
public class Client : IClientModel
{
public string ClientFIO { get; private set; } = string.Empty;
public string Email { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int Id { get; private set; }
public string ClientFIO { get; private set; } = string.Empty;
public string Email { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public static Client? Create(ClientBindingModel model)
{
@ -27,7 +23,7 @@ namespace CarpentryWorkshopFileImplement.Models
{
return null;
}
return new()
return new Client()
{
Id = model.Id,
ClientFIO = model.ClientFIO,
@ -41,12 +37,12 @@ namespace CarpentryWorkshopFileImplement.Models
{
return null;
}
return new()
return new Client()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ClientFIO = element.Element("FIO")!.Value,
ClientFIO = element.Element("ClientFIO")!.Value,
Email = element.Element("Email")!.Value,
Password = element.Element("Password")!.Value,
Password = element.Element("Password")!.Value
};
}
@ -66,14 +62,13 @@ namespace CarpentryWorkshopFileImplement.Models
Id = Id,
ClientFIO = ClientFIO,
Email = Email,
Password = Password,
Password = Password
};
public XElement GetXElement => new("Client",
new XAttribute("Id", Id),
new XElement("FIO", ClientFIO),
new XElement("ClientFIO", ClientFIO),
new XElement("Email", Email),
new XElement("Password", Password)
);
new XElement("Password", Password));
}
}

View File

@ -0,0 +1,87 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
using System.Xml.Linq;
namespace CarpentryWorkshopFileImplement.Models
{
public class Message : 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; }
public string Subject { get; private set; } = string.Empty;
public string Body { get; private set; } = string.Empty;
public static Message? Create(MessageInfoBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Body = model.Body,
Subject = model.Subject,
DateDelivery = model.DateDelivery,
SenderName = model.SenderName,
ClientId = model.ClientId,
MessageId = model.MessageId
};
}
public static Message? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
Body = element.Attribute("Body")!.Value,
Subject = element.Attribute("Subject")!.Value,
DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value),
SenderName = element.Attribute("SenderName")!.Value,
ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value),
MessageId = element.Attribute("MessageId")!.Value,
};
}
internal void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
SenderName = model.SenderName;
DateDelivery = model.DateDelivery;
Subject = model.Subject;
Body = model.Body;
}
public MessageInfoViewModel GetViewModel => new()
{
Body = Body,
Subject = Subject,
DateDelivery = DateDelivery,
SenderName = SenderName,
ClientId = ClientId,
MessageId = MessageId
};
public XElement GetXElement => new("MessageInfo",
new XAttribute("Subject", Subject),
new XAttribute("Body", Body),
new XAttribute("ClientId", ClientId),
new XAttribute("MessageId", MessageId),
new XAttribute("SenderName", SenderName),
new XAttribute("DateDelivery", DateDelivery)
);
}
}

View File

@ -10,6 +10,7 @@ namespace CarpentryWorkshopListImplement
public List<Wood> Woods { get; set; }
public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
public List<Message> Messages { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
@ -17,6 +18,7 @@ namespace CarpentryWorkshopListImplement
Woods = new List<Wood>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
Messages = new List<Message>();
}
public static DataListSingleton GetInstance()
{

View File

@ -3,11 +3,6 @@ using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopListImplement.Implements
{
@ -18,63 +13,6 @@ namespace CarpentryWorkshopListImplement.Implements
{
_source = DataListSingleton.GetInstance();
}
public ClientViewModel? Delete(ClientBindingModel model)
{
for (int i = 0; i < _source.Clients.Count; ++i)
{
if (_source.Clients[i].Id == model.Id)
{
var element = _source.Clients[i];
_source.Clients.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
if (model.Id.HasValue)
{
foreach (var client in _source.Clients)
{
if (client.Id == model.Id)
{
return client.GetViewModel;
}
}
}
else if (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Password))
{
foreach (var client in _source.Clients)
{
if (client.Email == model.Email && client.Password == model.Password)
{
return client.GetViewModel;
}
}
}
return null;
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
var result = new List<ClientViewModel>();
if (string.IsNullOrEmpty(model.Email))
{
return result;
}
foreach (var client in _source.Clients)
{
if (client.Email.Contains(model.Email))
{
result.Add(client.GetViewModel);
}
}
return result;
}
public List<ClientViewModel> GetFullList()
{
var result = new List<ClientViewModel>();
@ -84,7 +22,36 @@ namespace CarpentryWorkshopListImplement.Implements
}
return result;
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
var result = new List<ClientViewModel>();
if (string.IsNullOrEmpty(model.ClientFIO))
{
return result;
}
foreach (var client in _source.Clients)
{
if (client.ClientFIO.Contains(model.ClientFIO))
{
result.Add(client.GetViewModel);
}
}
return result;
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
foreach (var client in _source.Clients)
{
if (model.Id.HasValue && model.Id == client.Id)
return client.GetViewModel;
if (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Password) &&
client.Email.Equals(model.Email) && client.Password.Equals(model.Password))
return client.GetViewModel;
if (!string.IsNullOrEmpty(model.Email) && client.Email.Equals(model.Email))
return client.GetViewModel;
}
return null;
}
public ClientViewModel? Insert(ClientBindingModel model)
{
model.Id = 1;
@ -103,7 +70,6 @@ namespace CarpentryWorkshopListImplement.Implements
_source.Clients.Add(newClient);
return newClient.GetViewModel;
}
public ClientViewModel? Update(ClientBindingModel model)
{
foreach (var client in _source.Clients)
@ -116,5 +82,18 @@ namespace CarpentryWorkshopListImplement.Implements
}
return null;
}
public ClientViewModel? Delete(ClientBindingModel model)
{
for (int i = 0; i < _source.Clients.Count; ++i)
{
if (_source.Clients[i].Id == model.Id)
{
var element = _source.Clients[i];
_source.Clients.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,81 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopListImplement.Models;
namespace CarpentryWorkshopListImplement.Implements
{
internal class MessageInfoStorage : IMessageInfoStorage
{
private readonly DataListSingleton _source;
public MessageInfoStorage()
{
_source = DataListSingleton.GetInstance();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (model.MessageId == null)
{
return null;
}
foreach (var message in _source.Messages)
{
if (model.MessageId.Equals(message.MessageId))
return message.GetViewModel;
}
return null;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
if (!model.ClientId.HasValue)
{
return new();
}
var result = new List<MessageInfoViewModel>();
foreach (var item in _source.Messages)
{
if (item.ClientId == model.ClientId)
{
result.Add(item.GetViewModel);
}
}
return result;
}
public List<MessageInfoViewModel> GetFullList()
{
var result = new List<MessageInfoViewModel>();
foreach (var item in _source.Messages)
{
result.Add(item.GetViewModel);
}
return result;
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
var newMessage = Message.Create(model);
if (newMessage == null)
{
return null;
}
_source.Messages.Add(newMessage);
return newMessage.GetViewModel;
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
foreach (var massage in _source.Messages)
{
if (massage.MessageId == model.MessageId)
{
massage.Update(model);
return massage.GetViewModel;
}
}
return null;
}
}
}

View File

@ -1,18 +1,13 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopListImplement.Models
{
public class Client : IClientModel
{
public int Id { get; set; }
public string ClientFIO { get; set; } = string.Empty;
public int Id { get; private set; }
public string ClientFIO { get; private set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public static Client? Create(ClientBindingModel? model)
@ -44,7 +39,7 @@ namespace CarpentryWorkshopListImplement.Models
Id = Id,
ClientFIO = ClientFIO,
Email = Email,
Password = Password
Password = Password,
};
}
}

View File

@ -0,0 +1,58 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
namespace CarpentryWorkshopListImplement.Models
{
public class Message : 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 static Message? Create(MessageInfoBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Body = model.Body,
Subject = model.Subject,
DateDelivery = model.DateDelivery,
SenderName = model.SenderName,
ClientId = model.ClientId,
MessageId = model.MessageId
};
}
public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
SenderName = model.SenderName;
DateDelivery = model.DateDelivery;
Subject = model.Subject;
Body = model.Body;
}
public MessageInfoViewModel GetViewModel => new()
{
Body = Body,
Subject = Subject,
DateDelivery = DateDelivery,
SenderName = SenderName,
ClientId = ClientId,
MessageId = MessageId
};
}
}

View File

@ -11,13 +11,14 @@ namespace CarpentryWorkshopRestApi.Controllers
public class ClientController : Controller
{
private readonly ILogger _logger;
private readonly IClientLogic _logic;
private readonly IMessageInfoLogic _mailLogic;
public ClientController(IClientLogic logic, ILogger<ClientController> logger)
public ClientController(IClientLogic logic, ILogger<ClientController> logger, IMessageInfoLogic mailLogic)
{
_logger = logger;
_logic = logic;
_mailLogic = mailLogic;
}
[HttpGet]
@ -30,7 +31,6 @@ namespace CarpentryWorkshopRestApi.Controllers
Email = login,
Password = password
});
}
catch (Exception ex)
{
@ -66,5 +66,22 @@ namespace CarpentryWorkshopRestApi.Controllers
throw;
}
}
[HttpGet]
public List<MessageInfoViewModel>? GetMessages(int clientId)
{
try
{
return _mailLogic.ReadList(new MessageInfoSearchModel
{
ClientId = clientId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения писем клиента");
throw;
}
}
}
}

View File

@ -1,4 +1,6 @@
using CarpentryWorkshopBusinessLogic.BusinessLogics;
using CarpentryWorkshopBusinessLogic.MailWorker;
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopDatabaseImplement.Implements;
@ -6,35 +8,49 @@ using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.SetMinimumLevel(LogLevel.Trace);
// Add services to the container.
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IWoodStorage, WoodStorage>();
builder.Services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic,ClientLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IWoodLogic, WoodLogic>();
builder.Services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "ComputersShopRestApi",
Version = "v1"
});
c.SwaggerDoc("v1", new OpenApiInfo { Title = "CarpentryWorkshopRestApi", Version = "v1" });
});
var app = builder.Build();
var mailSender = app.Services.GetService<AbstractMailWorker>();
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())
{
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ComputersShopRestApi v1"));
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CarpentryWorkshopRestApi v1"));
}
app.UseHttpsRedirection();

View File

@ -5,5 +5,12 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "mailworker2024@gmail.com",
"MailPassword": "lab7zxcqwe"
}

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SmtpClientHost" value="smtp.gmail.com" />
<add key="SmtpClientPort" value="587" />
<add key="PopHost" value="pop.gmail.com" />
<add key="PopPort" value="995" />
<add key="MailLogin" value="mailworker2024@gmail.com" />
<add key="MailPassword" value="lab7zxcqwe" />
</appSettings>
</configuration>

View File

@ -0,0 +1,60 @@
namespace CarpentryWorkshopView
{
partial class FormMail
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(3, 3);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(794, 445);
dataGridView.TabIndex = 0;
//
// FormMail
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridView);
Name = "FormMail";
Text = "Эл. письма";
Load += FormMail_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,56 @@
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CarpentryWorkshopView
{
public partial class FormMail : Form
{
private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic;
public FormMail(ILogger<FormMail> logger, IMessageInfoLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["MessageId"].Visible = false;
dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка писем");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки писем");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void FormMail_Load(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

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

View File

@ -45,13 +45,14 @@
ButtonOrderReady = new Button();
ButtonIssuedOrder = new Button();
ButtonRef = new Button();
письмаToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, исполнителиToolStripMenuItem });
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, исполнителиToolStripMenuItem, письмаToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1174, 24);
@ -189,6 +190,13 @@
ButtonRef.UseVisualStyleBackColor = true;
ButtonRef.Click += ButtonRef_Click;
//
// письмаToolStripMenuItem
//
письмаToolStripMenuItem.Name = "письмаToolStripMenuItem";
письмаToolStripMenuItem.Size = new Size(62, 20);
письмаToolStripMenuItem.Text = "Письма";
письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -230,5 +238,6 @@
private ToolStripMenuItem ClientsToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem письмаToolStripMenuItem;
}
}

View File

@ -197,5 +197,13 @@ namespace CarpentryWorkshopView
form.ShowDialog();
}
}
private void письмаToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormMail));
if (service is FormMail form)
{
form.ShowDialog();
}
}
}
}

View File

@ -7,6 +7,8 @@ using CarpentryWorkshopDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using CarpentryWorkshopBusinessLogic.MailWorker;
using CarpentryWorkshopContracts.BindingModels;
namespace CarpentryWorkshopView
@ -27,6 +29,26 @@ namespace CarpentryWorkshopView
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
try
{
var mailSender = _serviceProvider.GetService<AbstractMailWorker>();
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<ILogger>();
logger?.LogError(ex, "Error");
}
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
private static void ConfigureServices(ServiceCollection services)
@ -41,6 +63,7 @@ namespace CarpentryWorkshopView
services.AddTransient<IWoodStorage, WoodStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
@ -48,7 +71,9 @@ namespace CarpentryWorkshopView
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
@ -66,6 +91,8 @@ namespace CarpentryWorkshopView
services.AddTransient<FormReportOrders>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormMail>();
}
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck();
}
}