This commit is contained in:
shadowik 2023-05-20 03:33:58 +04:00
commit 7cfaadd8d0
20 changed files with 185 additions and 256 deletions

View File

@ -1,33 +0,0 @@
using BankYouBankruptContracts.BindingModels;
using BankYouBankruptContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankYouBankruptBusinessLogic.BusinessLogics
{
public class MessageInfoLogic : IMessageInfoLogic
{
private readonly ILogger _logger;
//private readonly IMessageInfoStorage _messageInfoStorage;
public MessageInfoLogic(ILogger<MessageInfoLogic> logger)
{
_logger = logger;
}
public bool Create(MessageInfoBindingModel model)
{
throw new NotImplementedException();
}
public bool Update(MessageInfoBindingModel model)
{
throw new NotImplementedException();
}
}
}

View File

@ -1,4 +1,5 @@
using BankYouBankruptBusinessLogic.OfficePackage;
using BankYouBankruptBusinessLogic.MailWorker;
using BankYouBankruptBusinessLogic.OfficePackage;
using BankYouBankruptBusinessLogic.OfficePackage.HelperModels;
using BankYouBankruptContracts.BindingModels;
using BankYouBankruptContracts.BusinessLogicsContracts;
@ -18,26 +19,22 @@ namespace BankYouBankruptBusinessLogic.BusinessLogics
public class ReportCashierLogic : IReportCashierLogic
{
private readonly IMoneyTransferStorage _moneyTransferStorage;
private readonly ICashWithdrawalStorage _cashWithdrawalStorage;
private readonly IClientStorage _clientStorage;
private readonly IDebitingStorage _debitingStorage;
private readonly ICardStorage _cardStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
//инициализируем поля класса через контейнер
public ReportCashierLogic(IMoneyTransferStorage moneyTransferStorage, ICashWithdrawalStorage cashWithdrawalStorage,
private readonly MailKitWorker _mailKitWorker;
//инициализируем поля класса через контейнер
public ReportCashierLogic(IMoneyTransferStorage moneyTransferStorage, ICashWithdrawalStorage cashWithdrawalStorage,
IClientStorage clientStorage, AbstractSaveToExcel saveToExcel,
AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf,
IDebitingStorage debitingStorage, ICardStorage cardStorage)
IDebitingStorage debitingStorage, ICardStorage cardStorage, MailKitWorker mailKitWorker)
{
_moneyTransferStorage = moneyTransferStorage;
_cashWithdrawalStorage = cashWithdrawalStorage;
@ -48,6 +45,8 @@ namespace BankYouBankruptBusinessLogic.BusinessLogics
_clientStorage = clientStorage;
_debitingStorage = debitingStorage;
_cardStorage = cardStorage;
_mailKitWorker = mailKitWorker;
}
//формирование списка переводов между счетами за период
@ -121,8 +120,8 @@ namespace BankYouBankruptBusinessLogic.BusinessLogics
return client.Surname + " " + client.Name + " " + client.Patronymic;
}
//Сохранение мороженных в файл-Word
public void SaveAccountsToWordFile(ReportBindingModel model)
//Сохранение мороженных в файл-Word
public void SaveAccountsToWordFile(ReportBindingModel model)
{
_saveToWord.CreateDoc(new WordInfo
{
@ -165,8 +164,20 @@ namespace BankYouBankruptBusinessLogic.BusinessLogics
ReportCashWithdrawal = listCashWithdrawals
});
//возврат полученных списков для отображения на вебе
return new ReportCashierViewModelForHTML
byte[] pdf = System.IO.File.ReadAllBytes("C:\\Users\\Programmist73\\Desktop\\Практика\\2-й курс\\4-й семестр\\CourseWork_BankYouBankrupt\\BankYouBankrupt\\BankYouBankruptRestAPI\\Отчёт_по_счетам.pdf");
_mailKitWorker.SendMailAsync(new()
{
MailAddress = model.Email,
Subject = "Отчёт по счетам",
Text = $"За период с {model.DateFrom} " +
$"по {model.DateTo}.",
File = pdf,
Role = model.Role
});
//возврат полученных списков для отображения на вебе
return new ReportCashierViewModelForHTML
{
ReportCashWithdrawal = listCashWithdrawals,

View File

@ -13,6 +13,12 @@ using BankYouBankruptContracts.ViewModels.Client.Reports;
using BankYouBankruptContracts.ViewModels;
using BankYouBankruptDataModels.Enums;
using BankYouBankruptContracts.ViewModels.Client.Default;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Net.Mail;
using System.Reflection.PortableExecutable;
using Spire.Pdf.Graphics;
using DocumentFormat.OpenXml.Packaging;
using BankYouBankruptBusinessLogic.MailWorker;
namespace BankYouBankruptBusinessLogic.BusinessLogics
{
@ -22,23 +28,30 @@ namespace BankYouBankruptBusinessLogic.BusinessLogics
private readonly IDebitingStorage _debitingStorage;
private readonly ICardStorage _cardStorage;
private readonly IMoneyTransferStorage _moneyTransferStorage;
private readonly IClientStorage _clientStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
private readonly MailKitWorker _mailKitWorker;
public ReportClientLogic(ICreditingStorage creditingStorage, IDebitingStorage debitingStorage,
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf,
ICardStorage cardStorage, IMoneyTransferStorage moneyTransferStorage)
ICardStorage cardStorage, IMoneyTransferStorage moneyTransferStorage,
MailKitWorker mailKitWorker, IClientStorage clientStorage)
{
_creditingStorage = creditingStorage;
_debitingStorage = debitingStorage;
_cardStorage = cardStorage;
_moneyTransferStorage = moneyTransferStorage;
_clientStorage = clientStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
_mailKitWorker = mailKitWorker;
}
public List<ReportClientViewModel>? GetCrediting(ReportBindingModel model)
@ -136,7 +149,7 @@ namespace BankYouBankruptBusinessLogic.BusinessLogics
return totalList;
}
public void SaveToExcelFile(ReportBindingModel model, OfficeOperationEnum operationEnum)
public void SaveToExcelFile(ReportBindingModel model, OfficeOperationEnum operationEnum)
{
if(operationEnum == OfficeOperationEnum.Между_cчетами)
{
@ -216,7 +229,19 @@ namespace BankYouBankruptBusinessLogic.BusinessLogics
DateTo = model.DateTo!.Value,
ReportCrediting = listCreditings,
ReportDebiting = listDebitings
});
});
byte[] pdf = System.IO.File.ReadAllBytes("C:\\Users\\Programmist73\\Desktop\\Практика\\2-й курс\\4-й семестр\\CourseWork_BankYouBankrupt\\BankYouBankrupt\\BankYouBankruptRestAPI\\Отчёт_поартам.pdf");
_mailKitWorker.SendMailAsync(new()
{
MailAddress = model.Email,
Subject = "Отчёт по картам",
Text = $"За период с {model.DateFrom} " +
$"по {model.DateTo}.",
File = pdf,
Role = model.Role
});
//возврат полученных списков для отображения на вебе
return new ReportClientViewModelForHTML

View File

@ -1,107 +0,0 @@
using BankYouBankruptContracts.BindingModels;
using BankYouBankruptContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankYouBankruptBusinessLogic.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<AbstractMailWorker> 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<List<MessageInfoBindingModel>> ReceiveMailAsync();
}
}

View File

@ -10,82 +10,72 @@ using System.Text;
using System.Threading.Tasks;
using MailKit.Net.Pop3;
using MailKit.Security;
using BankYouBankruptDataModels.Enums;
namespace BankYouBankruptBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
//класс, отвечающий за отправку письма
public class MailKitWorker
{
public MailKitWorker(ILogger<MailKitWorker> logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic)
: base(logger, messageInfoLogic, clientLogic) { }
private string _mailLogin = string.Empty;
protected override async Task SendMailAsync(MailSendInfoBindingModel info)
private string _mailPassword = string.Empty;
private string _smtpClientHost = string.Empty;
private int _smtpClientPort;
private readonly ILogger logger;
public MailKitWorker(ILogger<MailKitWorker> logger)
{
this.logger = logger;
}
public void MailConfig(MailConfigBindingModel config)
{
_mailLogin = config.MailLogin;
_mailPassword = config.MailPassword;
_smtpClientHost = config.SmtpClientHost;
_smtpClientPort = config.SmtpClientPort;
}
public async void SendMailAsync(MailSendInfoBindingModel info)
{
using var objMailMessage = new MailMessage();
using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
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;
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;
MemoryStream ms = new(info.File);
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
if(info.Role == MailsEnum.Клиент)
{
objMailMessage.Attachments.Add(new Attachment(ms, "Отчёт_поартам.pdf", "application/pdf"));
}
else
{
objMailMessage.Attachments.Add(new Attachment(ms, "Отчёт_по_счетам.pdf", "application/pdf"));
}
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch (Exception)
{
throw;
}
}
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
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
{
DateDelivery = message.Date.DateTime,
MessageId = message.MessageId,
SenderName = mail.Address,
Subject = message.Subject,
Body = message.TextBody
});
}
}
}
catch (AuthenticationException)
{ }
finally
{
client.Disconnect(true);
}
});
return list;
}
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch (Exception)
{
throw;
}
}
}
}

View File

@ -602,6 +602,7 @@ namespace BankYouBankruptCashierApp.Controllers
return View(APICashier.PostRequestReport<ReportCashierViewModelForHTML, ReportSupportBindingModel>("api/Report/CreateCashierReport", new ReportSupportBindingModel()
{
ClientId = clientId,
Email = APICashier.Cashier.Email,
DateFrom = dateFrom,
DateTo = dateTo
}));

View File

@ -318,7 +318,8 @@ namespace BankYouBankruptClientApp.Controllers
return View(APIClient.PostRequestReport<ReportClientViewModelForHTML, ReportSupportBindingModel>("api/Report/CreateClientReport", new ReportSupportBindingModel()
{
DateFrom = dateFrom,
DateTo = dateTo
DateTo = dateTo,
Email = APIClient.Client.Email
}));
}

View File

@ -17,8 +17,10 @@ namespace BankYouBankruptContracts.BindingModels
public int SmtpClientPort { get; set; }
//можно без них?
public string PopHost { get; set; } = string.Empty;
//можно без них?
public int PopPort { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using System;
using BankYouBankruptDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -14,5 +15,10 @@ namespace BankYouBankruptContracts.BindingModels
public string Subject { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
}
//для отправки pdf
public byte[] File { get; set; } = Array.Empty<byte>();
public MailsEnum Role { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using BankYouBankruptContracts.ViewModels.Client.Reports;
using BankYouBankruptDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
@ -22,5 +23,9 @@ namespace BankYouBankruptContracts.BindingModels
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public MailsEnum Role { get; set; }
public string? Email { get; set; }
}
}

View File

@ -20,5 +20,7 @@ namespace BankYouBankruptContracts.BindingModels
//для Excel отчёта клиента
public List<int>? CardList { get; set; }
public string? Email { get; set; }
}
}

View File

@ -1,20 +0,0 @@
using BankYouBankruptContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankYouBankruptContracts.BusinessLogicsContracts
{
public interface IMessageInfoLogic
{
//List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model);
//MessageInfoViewModel? ReadElement(MessageInfoSearchModel model);
bool Create(MessageInfoBindingModel model);
bool Update(MessageInfoBindingModel model);
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankYouBankruptContracts.ViewModels
{
public class FileViewModel
{
public byte[] Bytes { get; set; } = Array.Empty<byte>();
public int[] Test { get; set; } = Array.Empty<int>();
public string StringBytes { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankYouBankruptDataModels.Enums
{
public enum MailsEnum
{
Клиент = 0,
Кассир = 1
}
}

View File

@ -32,7 +32,15 @@ namespace BankYouBankruptDatabaseImplement.Implements
{
return null;
}
using var context = new BankYouBancruptDatabase();
//сработает для поиска почты для отправки файла
if(model.Id.HasValue && string.IsNullOrEmpty(model.Password))
{
return context.Clients.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
return context.Clients.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && !string.IsNullOrEmpty(model.Password) && x.Password == model.Password) ||
(model.Id.HasValue && x.Id == model.Id))

View File

@ -47,7 +47,9 @@ namespace BankYouBankruptRestAPI.Controllers
{
FileName = "Отчёт_поартам.pdf",
DateFrom = model.DateFrom,
DateTo = model.DateTo
DateTo = model.DateTo,
Role = MailsEnum.Клиент,
Email = model.Email
});
return result;
@ -70,8 +72,10 @@ namespace BankYouBankruptRestAPI.Controllers
FileName = "Отчёт_по_счетам.pdf",
ClientId = model.ClientId,
DateFrom = model.DateFrom,
DateTo = model.DateTo
});
DateTo = model.DateTo,
Role = MailsEnum.Кассир,
Email = model.Email
});
return result;
}

View File

@ -36,9 +36,7 @@ builder.Services.AddTransient<ICashWithdrawalLogic, CashWithdrawalLogic>();
builder.Services.AddTransient<IReportClientLogic, ReportClientLogic>();
builder.Services.AddSingleton<IReportCashierLogic, ReportCashierLogic>();
builder.Services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
builder.Services.AddTransient<AbstractMailWorker, MailKitWorker>();
builder.Services.AddSingleton<MailKitWorker>();
//общие классы формировани отчётов
builder.Services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
@ -58,7 +56,7 @@ builder.Services.AddSwaggerGen(c =>
var app = builder.Build();
//Mails Service
var mailSender = app.Services.GetService<AbstractMailWorker>();
var mailSender = app.Services.GetService<MailKitWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
@ -66,8 +64,6 @@ mailSender?.MailConfig(new MailConfigBindingModel
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.

View File

@ -5,5 +5,11 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"MailLogin": "uveselchak99@gmail.com",
"MailPassword": "nqkv jzzq fryi leao"
}