You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

432 lines
17 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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
{
/// <summary>
/// 邮件接收账户配置
/// </summary>
[ApiDescriptionSettings("Application", Name = "EmailUserAccountService", Order = 9)]
public class EmailUserAccountService : IEmailUserAccountService, IDynamicApiController, ITransient
{
private readonly SqlSugarRepository<EmailUserAccountInfo> _emailUserAccountInfoRepository;
private readonly SqlSugarRepository<EmailUserAccountParserRelationInfo> _emailUserAccountParserRelationInfoRepository;
private readonly SqlSugarRepository<EmailParserConfigInfo> _emailParserConfigInfoRepository;
private readonly SqlSugarRepository<EmailExcuteCodeInjectConfigInfo> _emailExcuteCodeInjectConfigInfoRepository;
private readonly ILogger<EmailUserAccountService> _logger;
public EmailUserAccountService(ILogger<EmailUserAccountService> logger,
SqlSugarRepository<EmailUserAccountInfo> emailUserAccountInfoRepository,
SqlSugarRepository<EmailUserAccountParserRelationInfo> emailUserAccountParserRelationInfoRepository,
SqlSugarRepository<EmailParserConfigInfo> emailParserConfigInfoRepository,
SqlSugarRepository<EmailExcuteCodeInjectConfigInfo> emailExcuteCodeInjectConfigInfoRepository)
{
_logger = logger;
_emailUserAccountInfoRepository = emailUserAccountInfoRepository;
_emailUserAccountParserRelationInfoRepository = emailUserAccountParserRelationInfoRepository;
_emailParserConfigInfoRepository = emailParserConfigInfoRepository;
_emailExcuteCodeInjectConfigInfoRepository = emailExcuteCodeInjectConfigInfoRepository;
}
#region 保存邮件账户配置
/// <summary>
/// 保存邮件账户配置
/// </summary>
/// <param name="info">邮件账户配置表信息</param>
/// <returns>返回回执</returns>
[HttpPost("/EmailUserAccount/Save")]
public async Task<TaskManageOrderResultDto> 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<EmailUserAccountInfo>();
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<EmailUserAccountInfo>();
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 获取邮件账户配置详情
/// <summary>
/// 获取邮件账户配置详情
/// </summary>
/// <param name="gid">邮件账户配置表主键</param>
/// <returns>返回回执</returns>
[HttpGet("/EmailUserAccount/GetInfo")]
public async Task<TaskManageOrderResultDto> 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<EmailUserAccountDto>();
var parList = _emailUserAccountParserRelationInfoRepository.AsQueryable().Filter(null, true)
.InnerJoin<EmailParserConfigInfo>((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 删除
/// <summary>
/// 删除
/// </summary>
/// <param name="gIds">邮件账户配置主键数组</param>
/// <returns>返回回执</returns>
[HttpPost("/EmailUserAccount/Delete")]
public async Task<TaskManageOrderResultDto> 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<TaskManageOrderResultDto> rltList = new List<TaskManageOrderResultDto>();
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 邮件账户配置台账查询
/// <summary>
/// 邮件账户配置台账查询
/// </summary>
/// <param name="QuerySearch">邮件账户配置台账查询请求</param>
/// <returns>返回结果</returns>
[HttpPost("/EmailUserAccount/GetPage")]
public async Task<SqlSugarPagedList<EmailUserAccountPageDto>> 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<EmailUserAccountDto, EmailUserAccountInfo>(QuerySearch.SortField);
var entities = await query
.OrderBy(entityOrderCol + (QuerySearch.descSort ? " desc " : " asc "))
.ToPagedListAsync(QuerySearch.PageNo, QuerySearch.PageSize);
return entities.Adapt<SqlSugarPagedList<EmailUserAccountPageDto>>();
}
#endregion
#region 检索邮件解析配置
/// <summary>
/// 检索邮件解析配置
/// </summary>
/// <param name="queryItem">检索条件</param>
/// <param name="topNum">返回记录最大条数(可以根据需要自助设定)</param>
/// <returns></returns>
[HttpGet("/EmailUserAccount/QueryEmailParserConfigList")]
public async Task<TaskManageOrderResultDto> QueryEmailParserConfigList([FromQuery] string queryItem, [FromQuery] int topNum = 10)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
var parList = _emailParserConfigInfoRepository.AsQueryable()
.InnerJoin<EmailExcuteCodeInjectConfigInfo>((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
}
}