| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using Newtonsoft.Json; |
| | | 3 | | using Newtonsoft.Json.Converters; |
| | | 4 | | using Newtonsoft.Json.Serialization; |
| | | 5 | | using SVETA.Api.Helpers.Authorize; |
| | | 6 | | using SVETA.Api.Services.Interfaces; |
| | | 7 | | using System; |
| | | 8 | | using System.IO; |
| | | 9 | | using System.Linq; |
| | | 10 | | using System.Collections.Generic; |
| | | 11 | | using Microsoft.Extensions.Options; |
| | | 12 | | using SVETA.Api.Data.Domain; |
| | | 13 | | using WinSolutions.Sveta.Common; |
| | | 14 | | using System.Net.Http; |
| | | 15 | | using System.Security.Claims; |
| | | 16 | | using MimeKit; |
| | | 17 | | using MailKit.Net.Smtp; |
| | | 18 | | using System.Threading.Tasks; |
| | | 19 | | using WinSolutions.Sveta.Server.Data.DataModel.Contexts; |
| | | 20 | | using WinSolutions.Sveta.Server.Data.DataModel.Entities; |
| | | 21 | | using WinSolutions.Sveta.Server.Services.Interfaces; |
| | | 22 | | using Microsoft.Extensions.Logging; |
| | | 23 | | using SVETA.Api.Data.DTO.Email; |
| | | 24 | | using SVETA.API.IntegrationTest.Common; |
| | | 25 | | using DocumentFormat.OpenXml.Office.CustomUI; |
| | | 26 | | |
| | | 27 | | namespace SVETA.Api.Services.Implements |
| | | 28 | | { |
| | | 29 | | public class EmailWorker : IEmailWorker |
| | | 30 | | { |
| | | 31 | | private readonly SvetaDbContext _db; |
| | | 32 | | private readonly ConfigurationsSettings _confsSettings; |
| | | 33 | | private readonly IEmailGateHistoryService _emailGateSettings; |
| | | 34 | | private readonly EmailSettings _emailSettings; |
| | | 35 | | private readonly HttpClient httpClient; |
| | | 36 | | private readonly ILogger<EmailWorker> _logger; |
| | | 37 | | |
| | 83 | 38 | | public EmailWorker(SvetaDbContext db, |
| | 83 | 39 | | ILogger<EmailWorker> logger, |
| | 83 | 40 | | IOptions<ConfigurationsSettings> confsSettings, IOptions<EmailSettings> emailSettings, IEmailGateHistoryServ |
| | 83 | 41 | | { |
| | 83 | 42 | | _db = db; |
| | 83 | 43 | | _confsSettings = confsSettings.Value; |
| | 83 | 44 | | _emailGateSettings = emailGateSettings; |
| | 83 | 45 | | _emailSettings = emailSettings.Value; |
| | 83 | 46 | | _logger = logger; |
| | 83 | 47 | | httpClient = new HttpClient(); |
| | 83 | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Отправляет почту |
| | | 52 | | /// </summary> |
| | | 53 | | /// <param name="email">адресат</param> |
| | | 54 | | /// <param name="subject">Тема</param> |
| | | 55 | | /// <param name="body">Тело</param> |
| | | 56 | | /// <param name="attach">файл с полным путем</param> |
| | | 57 | | /// <returns></returns> |
| | | 58 | | public async Task SendEmail(string email, string subject, string body, string attach = null) |
| | 0 | 59 | | { |
| | 0 | 60 | | byte[] fileBytes = null; |
| | 0 | 61 | | if (!string.IsNullOrWhiteSpace(attach)) |
| | 0 | 62 | | fileBytes = await File.ReadAllBytesAsync(attach); |
| | 0 | 63 | | var emailMessage = new MimeMessage(); |
| | 0 | 64 | | emailMessage.To.Add(new MailboxAddress(email)); |
| | 0 | 65 | | emailMessage.Subject = subject; |
| | 0 | 66 | | var bodyBuilder = new BodyBuilder(); |
| | 0 | 67 | | bodyBuilder.HtmlBody = body + "<br><br>"; |
| | 0 | 68 | | if (fileBytes != null) bodyBuilder.Attachments.Add(attach, fileBytes); |
| | 0 | 69 | | emailMessage.Body = bodyBuilder.ToMessageBody(); |
| | 0 | 70 | | using (var client = new SmtpClient()) |
| | 0 | 71 | | { |
| | 0 | 72 | | emailMessage.From.Add(new MailboxAddress(_confsSettings.GetConfValue("EmailSettings", "From"))); |
| | 0 | 73 | | await client.ConnectAsync(_confsSettings.GetConfValue("EmailSettings", "SmtpServer"), int.TryParse(_conf |
| | 0 | 74 | | await client.AuthenticateAsync(_confsSettings.GetConfValue("EmailSettings", "Login"), _confsSettings.Get |
| | 0 | 75 | | await client.SendAsync(emailMessage); |
| | 0 | 76 | | await client.DisconnectAsync(true); |
| | 0 | 77 | | } |
| | 0 | 78 | | } |
| | | 79 | | |
| | | 80 | | /// <summary> |
| | | 81 | | /// Отправляет email по шаблону |
| | | 82 | | /// </summary> |
| | | 83 | | /// <param name="templateId">id шаблона</param> |
| | | 84 | | /// <param name="subject">Тема письма</param> |
| | | 85 | | /// <param name="emailAddress">почта получателя</param> |
| | | 86 | | /// <param name="movement">документ. Может быть null, если в письме не требуется товарный состав документа</para |
| | | 87 | | /// <param name="parameters">словарь с переменными для шаблона</param> |
| | | 88 | | /// <returns></returns> |
| | | 89 | | public async Task SendEmailByPattern(int templateId, string subject, string emailAddress, Movement movement, Dic |
| | 152 | 90 | | { |
| | | 91 | | try |
| | 152 | 92 | | { |
| | 152 | 93 | | if (!_emailSettings.EmailGateSettings.EmailSendOn) |
| | 152 | 94 | | return; |
| | 0 | 95 | | if (movement != null) |
| | 0 | 96 | | parameters.Add("orderbody", PrepareBodyForPattern(movement)); //если передали документ, значит надо |
| | 0 | 97 | | var data = new EmailPatternRequestDTO() |
| | 0 | 98 | | { |
| | 0 | 99 | | TemplateId = templateId, |
| | 0 | 100 | | Topic = subject, |
| | 0 | 101 | | Emails = new List<EmailParameters> { new EmailParameters { |
| | 0 | 102 | | ToClientAddress = emailAddress, |
| | 0 | 103 | | Parameters = parameters |
| | 0 | 104 | | } } |
| | 0 | 105 | | }; |
| | | 106 | | |
| | 0 | 107 | | StringContent requestContent = StringContentCreator.CreateContent(data); |
| | 0 | 108 | | var response = await httpClient.PostAsync(_emailSettings.EmailGateSettings.EmailService + _emailSettings |
| | 0 | 109 | | var emailResponse = JsonConvert.DeserializeObject<EmailPatternResponseDTO>(await response.Content.ReadAs |
| | 0 | 110 | | if (!response.IsSuccessStatusCode) |
| | 0 | 111 | | _logger.LogError($"Не удалось отправить email через шаблон. Статус запроса {(int)response.StatusCode |
| | 0 | 112 | | await _emailGateSettings.Create(PrepareRecord(data, (int)response.StatusCode, emailResponse)); |
| | 0 | 113 | | } |
| | 0 | 114 | | catch (Exception e) |
| | 0 | 115 | | { |
| | 0 | 116 | | _logger.LogError($"Не удалось отправить email через шаблон"); |
| | 0 | 117 | | _logger.LogError(e.Message + "\n" + e.StackTrace); |
| | 0 | 118 | | } |
| | 152 | 119 | | } |
| | | 120 | | |
| | | 121 | | /// <summary> |
| | | 122 | | /// Создает html таблицу для товаров документа |
| | | 123 | | /// </summary> |
| | | 124 | | /// <param name="movement">документ</param> |
| | | 125 | | /// <returns></returns> |
| | | 126 | | private string PrepareBodyForPattern(Movement movement) |
| | 0 | 127 | | { |
| | 0 | 128 | | var body = "<table border=\"1\" cellspacing=\"0\"><tr>" + |
| | 0 | 129 | | "<th>Название товара</th>" + |
| | 0 | 130 | | "<th>Цена</th>" + |
| | 0 | 131 | | "<th>Кол-во</th>" + |
| | 0 | 132 | | "<th>Сумма</th>" + |
| | 0 | 133 | | "<tr/>"; |
| | 0 | 134 | | foreach (var item in movement.Items) |
| | 0 | 135 | | body += "<tr>" + |
| | 0 | 136 | | $"<td>{item.Good.Name}</td>" + |
| | 0 | 137 | | $"<td>{item.Price}</td>" + |
| | 0 | 138 | | $"<td>{item.Quantity}</td>" + |
| | 0 | 139 | | $"<td>{(item.Price * item.Quantity).ToString("F2")}</td>" + |
| | 0 | 140 | | "</tr>"; |
| | 0 | 141 | | body += "<tr>" + |
| | 0 | 142 | | "<td colspan=\"3\">Итого</td>" + |
| | 0 | 143 | | $"<td>{movement.PrepaimentSum}</td>" + |
| | 0 | 144 | | "</tr></table>"; |
| | 0 | 145 | | return body; |
| | 0 | 146 | | } |
| | | 147 | | |
| | | 148 | | /// <summary> |
| | | 149 | | /// Преобразует объект EmailPatternRequestDTO в EmailGateHistory |
| | | 150 | | /// </summary> |
| | | 151 | | /// <param name="data">объект EmailPatternRequestDTO</param> |
| | | 152 | | /// <param name="statusCode">код ответа от смс гейта</param> |
| | | 153 | | /// <param name="emailResponse">текст ответа в объекте EmailPatternResponseDTO</param> |
| | | 154 | | /// <returns></returns> |
| | 0 | 155 | | private EmailGateHistory PrepareRecord(EmailPatternRequestDTO data, int statusCode, EmailPatternResponseDTO emai |
| | 0 | 156 | | { |
| | 0 | 157 | | TemplateId = data.TemplateId, |
| | 0 | 158 | | Subject = data.Topic, |
| | 0 | 159 | | EmailAddress = data.Emails.FirstOrDefault().ToClientAddress, |
| | 0 | 160 | | StatusCode = statusCode, |
| | 0 | 161 | | ResponseStatus = emailResponse.Status, |
| | 0 | 162 | | ResponseText = emailResponse.StatusText |
| | 0 | 163 | | }; |
| | | 164 | | } |
| | | 165 | | } |