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 SqlSugar; 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 = "EmailParserConfigServices", Order = 9)] public class EmailParserConfigService : IEmailParserConfigService, IDynamicApiController, ITransient { private readonly SqlSugarRepository _emailParserConfigInfoRepository; private readonly SqlSugarRepository _emailUserAccountParserRelationInfoRepository; private readonly SqlSugarRepository _emailExcuteCodeInjectConfigInfoRepository; private readonly ILogger _logger; public EmailParserConfigService(ILogger logger, SqlSugarRepository emailParserConfigInfoRepository, SqlSugarRepository emailUserAccountParserRelationInfoRepository, SqlSugarRepository emailExcuteCodeInjectConfigInfoRepository) { _logger = logger; _emailParserConfigInfoRepository = emailParserConfigInfoRepository; _emailUserAccountParserRelationInfoRepository = emailUserAccountParserRelationInfoRepository; _emailExcuteCodeInjectConfigInfoRepository = emailExcuteCodeInjectConfigInfoRepository; } /// /// 保存邮件解析配置 /// /// 邮件解析配置信息 /// 返回回执 [HttpPost("/EmailParserConfig/Save")] public async Task Save(EmailParserConfigDto info) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { /* 1、邮箱账户不能重复 2、邮箱账户需要做正则匹配。 */ string gid = info.GID; if (string.IsNullOrWhiteSpace(info.ParserCode)) throw Oops.Oh($"解析器代码不能为空", typeof(InvalidOperationException)); if (string.IsNullOrWhiteSpace(info.ParserName)) throw Oops.Oh($"解析器名称不能为空", typeof(InvalidOperationException)); if (string.IsNullOrWhiteSpace(info.SubjectRegexPattern) && string.IsNullOrWhiteSpace(info.BodyRegexPattern) && string.IsNullOrWhiteSpace(info.SenderRegexPattern) && string.IsNullOrWhiteSpace(info.AttachRegexPattern)) throw Oops.Oh($"邮件标题匹配、邮件正文匹配、邮件发送人匹配、邮件附件匹配至少要填写一项匹配", typeof(InvalidOperationException)); DateTime nowDate = DateTime.Now; if (string.IsNullOrWhiteSpace(gid)) { var num = _emailParserConfigInfoRepository.AsQueryable().Count(a => a.PARSER_CODE.Equals(info.ParserCode)); 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 _emailParserConfigInfoRepository.InsertAsync(entity); } else { var num = _emailParserConfigInfoRepository.AsQueryable().Count(a => a.PARSER_CODE.Equals(info.ParserCode) && a.GID != gid); if (num > 0) throw Oops.Oh($"解析器代码不能重复", typeof(InvalidOperationException)); var model = _emailParserConfigInfoRepository.AsQueryable() .First(a => a.GID == gid); var entity = info.Adapt(); entity.UpdatedTime = nowDate; entity.UpdatedUserId = UserManager.UserId; entity.UpdatedUserName = UserManager.Name; await _emailParserConfigInfoRepository.AsUpdateable(entity) .IgnoreColumns(it => new { it.TenantId, it.TenantName, it.CreatedTime, it.CreatedUserId, it.CreatedUserName, it.IsDeleted }).ExecuteCommandAsync(); } result.succ = true; result.msg = "保存成功"; result.ext = gid; } catch (Exception ex) { result.succ = false; result.msg = $"保存邮件执行代码注入配置异常,原因:{ex.Message}"; } return result; } #region 获取邮件解析配置详情 /// /// 获取邮件解析配置详情 /// /// 邮件解析配置主键 /// 返回回执 [HttpGet("/EmailParserConfig/GetInfo")] public async Task GetInfo(string gid) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { if (string.IsNullOrWhiteSpace(gid)) { throw Oops.Oh($"邮件解析配置主键不能为空", typeof(InvalidOperationException)); } var model = await _emailParserConfigInfoRepository.AsQueryable() .FirstAsync(a => a.GID == gid); if (model == null) throw Oops.Oh($"邮件解析配置获取失败,邮件解析配置不存在或已作废", typeof(InvalidOperationException)); var showModel = model.Adapt(); if(!string.IsNullOrWhiteSpace(model.INJECT_ID)) { var injectModel = _emailExcuteCodeInjectConfigInfoRepository.AsQueryable() .First(a => a.GID == model.INJECT_ID); if(injectModel != null) { showModel.InjectCode = injectModel.INJECT_CODE; showModel.InjectName = injectModel.INJECT_NAME; showModel.InjectFullName = injectModel.INJECT_NAME; } } result.succ = true; result.ext = showModel; } catch (Exception ex) { result.succ = false; result.msg = $"获取邮件解析配置异常,原因:{ex.Message}"; } return result; } #endregion #region 删除 /// /// 删除 /// /// 邮件解析配置主键数组 /// 返回回执 [HttpPost("/EmailParserConfig/Delete")] public async Task Delete([FromBody] string[] gIds) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { if (gIds.Length == 0) { throw Oops.Oh($"邮件解析配置主键数组不能为空", typeof(InvalidOperationException)); } var list = _emailParserConfigInfoRepository.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 _emailParserConfigInfoRepository.UpdateAsync(x => x.GID == record.GID, x => new EmailParserConfigInfo { IsDeleted = true }); await _emailUserAccountParserRelationInfoRepository.DeleteAsync(x => x.EMAIL_PARSER_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("/EmailParserConfig/GetPage")] public async Task> GetPageAsync(QueryEmailParserConfigDto QuerySearch) { var query = _emailParserConfigInfoRepository.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.ParserCode)) { query = query.Where(t => t.PARSER_CODE.Contains(QuerySearch.ParserCode)); } if (!string.IsNullOrWhiteSpace(QuerySearch.ParserName)) { query = query.Where(t => t.PARSER_NAME.Contains(QuerySearch.ParserName)); } if (!string.IsNullOrWhiteSpace(QuerySearch.SubjectRegexPattern)) { query = query.Where(t => t.SUBJECT_REGEX_PATTERN.Contains(QuerySearch.SubjectRegexPattern)); } if (!string.IsNullOrWhiteSpace(QuerySearch.BodyRegexPattern)) { query = query.Where(t => t.BODY_REGEX_PATTERN.Contains(QuerySearch.BodyRegexPattern)); } if (!string.IsNullOrWhiteSpace(QuerySearch.SenderRegexPattern)) { query = query.Where(t => t.SENDER_REGEX_PATTERN.Contains(QuerySearch.SenderRegexPattern)); } if (!string.IsNullOrWhiteSpace(QuerySearch.AttachRegexPattern)) { query = query.Where(t => t.ATTACH_REGEX_PATTERN.Contains(QuerySearch.AttachRegexPattern)); } 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 ? " desc " : " asc ")) .ToPagedListAsync(QuerySearch.PageNo, QuerySearch.PageSize); return entities.Adapt>(); } #endregion #region 检索邮件执行代码注入配置 /// /// 检索邮件执行代码注入配置 /// /// 检索条件 /// 返回记录最大条数(可以根据需要自助设定) /// [HttpGet("/EmailParserConfig/QueryExcuteCodeInjectConfigList")] public async Task QueryExcuteCodeInjectConfigList([FromQuery] string queryItem, [FromQuery] int topNum = 10) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { var parList = _emailExcuteCodeInjectConfigInfoRepository.AsQueryable().Filter(null, true) .WhereIF(!string.IsNullOrWhiteSpace(queryItem), inj => inj.INJECT_CODE.Contains(queryItem) || inj.INJECT_NAME.Contains(queryItem) || inj.INJECT_FULLNAME.Contains(queryItem)) .OrderBy(inj => inj.INJECT_NAME) .ToList(); var list = parList.Select(t => new EmailExcuteCodeInjectConfigDto { GID = t.GID, InjectCode = t.INJECT_CODE, InjectName = t.INJECT_NAME, InjectFullName = t.INJECT_FULLNAME }).ToList(); result.succ = true; result.ext = list; } catch (Exception ex) { result.succ = false; result.msg = $"检索邮件执行代码注入配置异常,原因:{ex.Message}"; } return result; } #endregion #region 检索所有使用此邮件解析配置邮箱列表 /// /// 检索所有使用此邮件解析配置邮箱列表 /// /// 邮件解析配置主键 /// [HttpGet("/EmailParserConfig/QueryUseParserConfigEmailList")] public async Task QueryUseParserConfigEmailList([FromQuery] string gid) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { var accountList = _emailParserConfigInfoRepository.AsQueryable() .InnerJoin((par,rela)=> par.GID == rela.EMAIL_PARSER_ID) .InnerJoin((par, rela,acc) => rela.EMAIL_ACCOUNT_ID == acc.GID) .Where(par=> par.GID == gid) .Select((par, rela, acc)=>acc) .ToList(); var list = accountList.Select(t => t.Adapt()).OrderBy(t=>t.EmailAccount).ToList(); result.succ = true; result.ext = list; } catch (Exception ex) { result.succ = false; result.msg = $"检索所有使用此邮件解析配置邮箱列表异常,原因:{ex.Message}"; } return result; } #endregion } }