using Furion.DependencyInjection; using Furion.DistributedIDGenerator; using Furion.DynamicApiController; using Furion.FriendlyException; using Mapster; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Myshipping.Application.Entity; using Myshipping.Application.Helper; using Myshipping.Core; using MySqlX.XDevAPI.Common; using NPOI.SS.Formula.PTG; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Myshipping.Application { /// /// 邮件接收账户配置 /// [ApiDescriptionSettings("Application", Name = "EmailUserAccountService", Order = 9)] public class EmailUserAccountService : IEmailUserAccountService, IDynamicApiController, ITransient { private readonly SqlSugarRepository _emailUserAccountInfoRepository; private readonly SqlSugarRepository _emailUserAccountParserRelationInfoRepository; private readonly SqlSugarRepository _emailParserConfigInfoRepository; private readonly SqlSugarRepository _emailExcuteCodeInjectConfigInfoRepository; private readonly ILogger _logger; public EmailUserAccountService(ILogger logger, SqlSugarRepository emailUserAccountInfoRepository, SqlSugarRepository emailUserAccountParserRelationInfoRepository, SqlSugarRepository emailParserConfigInfoRepository, SqlSugarRepository emailExcuteCodeInjectConfigInfoRepository) { _logger = logger; _emailUserAccountInfoRepository = emailUserAccountInfoRepository; _emailUserAccountParserRelationInfoRepository = emailUserAccountParserRelationInfoRepository; _emailParserConfigInfoRepository = emailParserConfigInfoRepository; _emailExcuteCodeInjectConfigInfoRepository = emailExcuteCodeInjectConfigInfoRepository; } #region 保存邮件账户配置 /// /// 保存邮件账户配置 /// /// 邮件账户配置表信息 /// 返回回执 [HttpPost("/EmailUserAccount/Save")] public async Task Save(EmailUserAccountDto info) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { /* 1、邮箱账户不能重复 2、邮箱账户需要做正则匹配。 */ string gid = info.GID; if(string.IsNullOrWhiteSpace(info.EmailAccount)) throw Oops.Oh($"邮件账户不能为空", typeof(InvalidOperationException)); if(!Regex.IsMatch(info.EmailAccount,"^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$")) throw Oops.Oh($"邮件账户格式错误,请使用正确的邮箱格式", typeof(InvalidOperationException)); DateTime nowDate = DateTime.Now; if (string.IsNullOrWhiteSpace(gid)) { var num = _emailUserAccountInfoRepository.AsQueryable().Count(a => a.EMAIL_ACCOUNT.Equals(info.EmailAccount)); if (num > 0) throw Oops.Oh($"邮件账户不能重复", typeof(InvalidOperationException)); gid = IDGen.NextID().ToString(); var entity = info.Adapt(); entity.GID = gid; entity.CreatedTime = nowDate; entity.UpdatedTime = nowDate; entity.CreatedUserId = UserManager.UserId; entity.CreatedUserName = UserManager.Name; await _emailUserAccountInfoRepository.InsertAsync(entity); if (info.ParserList != null && info.ParserList.Count > 0) { info.ParserList.ForEach(async b => { var rela = new EmailUserAccountParserRelationInfo { GID = IDGen.NextID().ToString(), EMAIL_ACCOUNT = entity.EMAIL_ACCOUNT, EMAIL_ACCOUNT_ID = gid, EMAIL_PARSER_ID = b.GID }; await _emailUserAccountParserRelationInfoRepository.InsertAsync(rela); }); } } else { var num = _emailUserAccountInfoRepository.AsQueryable().Count(a => a.EMAIL_ACCOUNT.Equals(info.EmailAccount) && a.GID != gid); if (num > 0) throw Oops.Oh($"邮件账户不能重复", typeof(InvalidOperationException)); var model = _emailUserAccountInfoRepository.AsQueryable() .First(a=>a.GID == gid); var entity = info.Adapt(); entity.UpdatedTime = nowDate; entity.UpdatedUserId = UserManager.UserId; entity.UpdatedUserName = UserManager.Name; await _emailUserAccountInfoRepository.AsUpdateable(entity) .IgnoreColumns(it => new { it.TenantId, it.TenantName, it.CreatedTime, it.CreatedUserId, it.CreatedUserName, it.IsDeleted }).ExecuteCommandAsync(); await _emailUserAccountParserRelationInfoRepository.DeleteAsync(x => x.EMAIL_ACCOUNT_ID == gid); if (info.ParserList != null && info.ParserList.Count > 0) { info.ParserList.ForEach(async b => { var rela = new EmailUserAccountParserRelationInfo { GID = IDGen.NextID().ToString(), EMAIL_ACCOUNT = entity.EMAIL_ACCOUNT, EMAIL_ACCOUNT_ID = gid, EMAIL_PARSER_ID = b.GID }; await _emailUserAccountParserRelationInfoRepository.InsertAsync(rela); }); } } result.succ = true; result.msg = "保存成功"; result.ext = gid; } catch (Exception ex) { result.succ = false; result.msg = $"保存邮件账户配置异常,原因:{ex.Message}"; } return result; } #endregion #region 获取邮件账户配置详情 /// /// 获取邮件账户配置详情 /// /// 邮件账户配置表主键 /// 返回回执 [HttpGet("/EmailUserAccount/GetInfo")] public async Task GetInfo(string gid) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { if (string.IsNullOrWhiteSpace(gid)) { throw Oops.Oh($"邮件账户配置主键不能为空", typeof(InvalidOperationException)); } var model = await _emailUserAccountInfoRepository.AsQueryable().FirstAsync(a => a.GID == gid); if (model == null) throw Oops.Oh($"邮件账户配置获取失败,邮件账户配置不存在或已作废", typeof(InvalidOperationException)); var showModel = model.Adapt(); var parList = _emailUserAccountParserRelationInfoRepository.AsQueryable().Filter(null, true) .InnerJoin((rela, par) => rela.EMAIL_PARSER_ID == par.GID) .Where(rela => rela.EMAIL_ACCOUNT_ID == model.GID) .Select((rela, par) => par).ToList(); if (parList.Count > 0) { showModel.ParserList = parList.Select(a => new EmailParserConfigDto { GID = a.GID, ParserCode = a.PARSER_CODE, ParserName = a.PARSER_NAME, }).ToList(); } result.succ = true; result.ext = showModel; } catch (Exception ex) { result.succ = false; result.msg = $"获取邮件账户配置异常,原因:{ex.Message}"; } return result; } #endregion #region 删除 /// /// 删除 /// /// 邮件账户配置主键数组 /// 返回回执 [HttpPost("/EmailUserAccount/Delete")] public async Task Delete([FromBody] string[] gIds) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { if (gIds.Length == 0) { throw Oops.Oh($"邮件账户配置主键数组不能为空", typeof(InvalidOperationException)); } var list = _emailUserAccountInfoRepository.AsQueryable() .Where(a => gIds.Contains(a.GID)).ToList(); if (list.Count == 0) throw Oops.Oh($"邮件账户配置获取失败,请确认邮件账户配置是否存在", typeof(InvalidOperationException)); if (list.Count != gIds.Length) throw Oops.Oh($"部分邮件账户配置获取失败,请确认邮件账户配置是否存在", typeof(InvalidOperationException)); List rltList = new List(); list.ForEach(async record => { await _emailUserAccountInfoRepository.UpdateAsync(x => x.GID == record.GID, x => new EmailUserAccountInfo { IsDeleted = true }); await _emailUserAccountParserRelationInfoRepository.DeleteAsync(x => x.EMAIL_ACCOUNT_ID == record.GID); }); result.succ = true; result.msg = "删除成功"; _logger.LogInformation("删除邮件账户配置成功 ids={id} user={usr}", gIds, UserManager.UserId); } catch (Exception ex) { result.succ = false; result.msg = $"删除邮件账户配置异常,原因:{ex.Message}"; } return result; } #endregion #region 邮件账户配置台账查询 /// /// 邮件账户配置台账查询 /// /// 邮件账户配置台账查询请求 /// 返回结果 [HttpPost("/EmailUserAccount/GetPage")] public async Task> GetPageAsync(QueryEmailUserAccountDto QuerySearch) { var query = _emailUserAccountInfoRepository.AsQueryable(); #region 查询条件 //接收时间起始 if (!string.IsNullOrWhiteSpace(QuerySearch.CreateBegin)) { DateTime currDate = DateTime.MinValue; if (!DateTime.TryParse(QuerySearch.CreateBegin, out currDate)) throw Oops.Oh($"创建日期起始日期格式错误,{QuerySearch.CreateBegin}"); query = query.Where(t => t.CreatedTime >= currDate); } //接收时间结束 if (!string.IsNullOrWhiteSpace(QuerySearch.CreateEnd)) { DateTime currDate = DateTime.MinValue; if (!DateTime.TryParse(QuerySearch.CreateEnd, out currDate)) throw Oops.Oh($"创建日期结束日期格式错误,{QuerySearch.CreateEnd}"); currDate = currDate.AddDays(1); query = query.Where(t => t.CreatedTime < currDate); } //更新时间起始 if (!string.IsNullOrWhiteSpace(QuerySearch.UpdateBegin)) { DateTime currDate = DateTime.MinValue; if (!DateTime.TryParse(QuerySearch.UpdateBegin, out currDate)) throw Oops.Oh($"更新时间起始日期格式错误,{QuerySearch.UpdateBegin}"); query = query.Where(t => t.UpdatedTime >= currDate); } //更新时间结束 if (!string.IsNullOrWhiteSpace(QuerySearch.UpdateEnd)) { DateTime currDate = DateTime.MinValue; if (!DateTime.TryParse(QuerySearch.UpdateEnd, out currDate)) throw Oops.Oh($"更新时间结束日期格式错误,{QuerySearch.UpdateEnd}"); currDate = currDate.AddDays(1); query = query.Where(t => t.UpdatedTime < currDate); } if (!string.IsNullOrWhiteSpace(QuerySearch.EmailAccount)) { query = query.Where(t => t.EMAIL_ACCOUNT.Contains(QuerySearch.EmailAccount)); } if (!string.IsNullOrWhiteSpace(QuerySearch.ReceiveServer)) { query = query.Where(t => t.RECEIVE_SERVER.Contains(QuerySearch.ReceiveServer)); } if (!string.IsNullOrWhiteSpace(QuerySearch.SmtpServer)) { query = query.Where(t => t.SMTP_SERVER.Contains(QuerySearch.SmtpServer)); } if (!string.IsNullOrWhiteSpace(QuerySearch.CreateUser)) { query = query.Where(t => t.CreatedUserName.Contains(QuerySearch.CreateUser)); } if (!string.IsNullOrWhiteSpace(QuerySearch.UpdateUser)) { query = query.Where(t => t.UpdatedUserName.Equals(QuerySearch.UpdateUser)); } #endregion string entityOrderCol = "CreatedTime"; //这里因为返回给前端的台账数据是DTO,所以这里排序时候需要转换成Entity对应的字段 if (!string.IsNullOrWhiteSpace(QuerySearch.SortField)) entityOrderCol = MapsterExtHelper.GetAdaptProperty(QuerySearch.SortField); var entities = await query .OrderBy(entityOrderCol + (QuerySearch.descSort ? " asc " : " desc ")) .ToPagedListAsync(QuerySearch.PageNo, QuerySearch.PageSize); return entities.Adapt>(); } #endregion #region 检索邮件解析配置 /// /// 检索邮件解析配置 /// /// 检索条件 /// 返回记录最大条数(可以根据需要自助设定) /// [HttpGet("/EmailUserAccount/QueryEmailParserConfigList")] public async Task QueryEmailParserConfigList([FromQuery] string queryItem, [FromQuery] int topNum = 10) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { var parList = _emailParserConfigInfoRepository.AsQueryable() .InnerJoin((par, inj) => par.INJECT_ID == inj.GID) .WhereIF(!string.IsNullOrWhiteSpace(queryItem), (par, inj) => par.PARSER_CODE.Contains(queryItem) || par.PARSER_NAME.Contains(queryItem) || inj.INJECT_CODE.Contains(queryItem) || inj.INJECT_NAME.Contains(queryItem) || inj.INJECT_FULLNAME.Contains(queryItem)) .OrderBy((par, inj) => par.PARSER_NAME) .Select((par, inj) => new { par = par, inj = inj }) .ToList(); var list = parList.Select(t => new EmailParserConfigWithInjectDto { ParserGid = t.par.GID, ParserCode = t.par.PARSER_CODE, ParserName = t.par.PARSER_NAME, InjectId = t.inj.GID, InjectCode = t.inj.INJECT_CODE, InjectName = t.inj.INJECT_NAME, InjectFullName = t.inj.INJECT_FULLNAME }).ToList(); result.succ = true; result.ext = list; } catch (Exception ex) { result.succ = false; result.msg = $"检索邮件解析配置异常,原因:{ex.Message}"; } return result; } #endregion } }