恢复定时任务配置

dev
嵇文龙 4 weeks ago
parent f4b9812e1d
commit 3063ae6f52

@ -49,6 +49,7 @@
<PackageReference Include="NPOI" Version="2.7.0" />
<PackageReference Include="Npoi.Mapper" Version="6.2.1" />
<PackageReference Include="Quartz" Version="3.13.0" />
<PackageReference Include="Quartz.AspNetCore" Version="3.13.0" />
<PackageReference Include="Quartz.Extensions.Hosting" Version="3.13.0" />
<PackageReference Include="RabbitMQ.Client" Version="6.5.0" />
<PackageReference Include="RazorEngineCore" Version="2024.4.1" />

@ -3,6 +3,7 @@ using DS.WMS.Core.QuarztJobs;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Quartz.AspNetCore;
namespace DS.Module.QuartzModuleInstall
{
@ -58,7 +59,7 @@ namespace DS.Module.QuartzModuleInstall
});
// 添加 Quartz 主机服务
services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
services.AddQuartzServer(q => q.WaitForJobsToComplete = true);
}
public static void AddOpQuartzModuleInstall(this IServiceCollection services, IConfiguration configuration)
@ -76,8 +77,7 @@ namespace DS.Module.QuartzModuleInstall
);
});
// 添加 Quartz 主机服务
services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
services.AddQuartzServer(q => q.WaitForJobsToComplete = true);
}
}
}

@ -1,100 +0,0 @@
//using System.Net.Http.Headers;
//using DS.Module.Core;
//using DS.WMS.Core.HangfireJob.Interface;
//using DS.WMS.Core.Sys.Entity;
//using Microsoft.Extensions.Configuration;
//using Microsoft.Extensions.DependencyInjection;
//using SqlSugar;
//namespace DS.WMS.Core.HangfireJob.Method
//{
// /// <summary>
// /// 自动费用模板后台任务
// /// </summary>
// public class FeeCustTemplateJobService : IFeeCustTemplateJobService
// {
// static readonly ApiFox api;
// ISqlSugarClient? db;
// IConfiguration configuration;
// static FeeCustTemplateJobService()
// {
// api = new ApiFox();
// }
// /// <summary>
// /// 初始化
// /// </summary>
// /// <param name="serviceProvider"></param>
// public FeeCustTemplateJobService(IServiceProvider serviceProvider)
// {
// db = serviceProvider.GetRequiredService<ISqlSugarClient>();
// configuration = serviceProvider.GetRequiredService<IConfiguration>();
// }
// /// <summary>
// /// 生成费用
// /// </summary>
// /// <returns></returns>
// public async Task GenerateFeesAsync()
// {
// db.QueryFilter.Clear();
// var dbLinks = await db.Queryable<Module.SqlSugar.SysTenantLink>().ToListAsync();
// foreach (var dbLink in dbLinks)
// {
// var adminUser = await db.Queryable<SysUser>()
// .Where(x => x.TenantId == dbLink.TenantId && x.Status == 0 && x.UserType == 1)
// .OrderByDescending(x => x.CreateTime)
// .Select(x => new
// {
// x.Id,
// x.UserName,
// x.Password,
// x.DefaultOrgId,
// x.DefaultOrgName,
// x.TenantId,
// x.TenantName
// }).FirstAsync();
// if (adminUser == null)
// {
// Console.WriteLine($"未能获取租户系统管理员租户ID{dbLink.TenantId}");
// continue;
// }
// var tokenModel = new JwtHelper.JwtTokenModel
// {
// Uid = adminUser.Id.ToString(),
// Name = adminUser.UserName,
// OrgId = adminUser.DefaultOrgId.ToString(),
// TenantId = adminUser.TenantId.ToString(),
// TenantName = adminUser.TenantName
// };
// var token = JwtHelper.Encrypt(tokenModel, false, true);
// await SendRequestAsync(token);
// }
// }
// internal async Task SendRequestAsync(string token)
// {
// if (api.BaseUri == null)
// {
// var baseUrl = configuration["AutoFeeTemplate:BaseUrl"];
// if (string.IsNullOrEmpty(baseUrl))
// throw new ApplicationException("未配置自动费用模板请求基础URL");
// api.BaseUri = new Uri(baseUrl, UriKind.Absolute);
// }
// api.DefaultHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
// var response = await api.SendRequestAsync(HttpMethod.Post, configuration["AutoFeeTemplate:GenerateFeesUrl"]!, new
// {
// etd = DateTime.Now.Date
// });
// if (!response.IsSuccessStatusCode)
// throw new ApplicationException("自动费用模板生成费用失败,详情查看日志");
// }
// }
//}

@ -1,185 +0,0 @@
//using DS.Module.Core;
//using DS.WMS.Core.HangfireJob.Dtos;
//using DS.WMS.Core.HangfireJob.Interface;
//using DS.WMS.Core.Op.Entity;
//using Microsoft.AspNetCore.Hosting;
//using Microsoft.Extensions.DependencyInjection;
//using MiniExcelLibs;
//using SqlSugar;
//namespace DS.WMS.Core.HangfireJob.Method
//{
// /// <summary>
// /// WSL报表服务
// /// </summary>
// public class WSLReportJobService : IWSLReportJobService
// {
// static readonly ApiFox api;
// ISqlSugarClient? db;
// Microsoft.Extensions.Configuration.IConfiguration config;
// IWebHostEnvironment hostEnvironment;
// static WSLReportJobService()
// {
// api = new ApiFox();
// }
// /// <summary>
// /// 初始化
// /// </summary>
// /// <param name="serviceProvider"></param>
// public WSLReportJobService(IServiceProvider serviceProvider)
// {
// db = serviceProvider.GetRequiredService<ISqlSugarClient>();
// config = serviceProvider.GetRequiredService<Microsoft.Extensions.Configuration.IConfiguration>();
// hostEnvironment = serviceProvider.GetRequiredService<IWebHostEnvironment>();
// }
// /// <summary>
// /// 生成报表
// /// </summary>
// /// <returns></returns>
// public async Task GeneratReportAsync()
// {
// string path = Path.Combine(hostEnvironment.WebRootPath, "templates", "WSL.xlsx");
// FileInfo templateFile = new FileInfo(path);
// if (!templateFile.Exists)
// throw new ApplicationException("未能在下列路径找到模板文件:" + path);
// db.QueryFilter.Clear();
// var dbLinks = await db.Queryable<Module.SqlSugar.SysTenantLink>().ToListAsync();
// SqlSugarClient? tenantDb = null;
// var today = DateTime.Now;
// var today0 = new DateTime(today.Year, today.Month, today.Day);
// var yesterday0 = today0.AddDays(-1).Date;
// var yesterday = new DateTime(yesterday0.Year, yesterday0.Month, yesterday0.Day, 23, 59, 59);
// var lastMonth = today.AddMonths(-1);
// var nextMonth = today.AddMonths(1);
// var startDate = new DateTime(lastMonth.Year, lastMonth.Month, lastMonth.Day);
// var endDate = new DateTime(nextMonth.Year, nextMonth.Month, nextMonth.Day, 23, 59, 59);
// try
// {
// foreach (var dbLink in dbLinks)
// {
// if (config["TaskMail:DefaultSetting:Tenant"] != dbLink.TenantId.ToString())
// continue;
// tenantDb = new SqlSugarClient(new ConnectionConfig
// {
// ConfigId = dbLink.Id,
// ConnectionString = dbLink.Connection,
// DbType = dbLink.DbType,
// IsAutoCloseConnection = true
// });
// WSLModel model = new()
// {
// Date = today.ToString("yyyy.MM.dd"),
// Month = today.ToString("yyyy.MM")
// };
// var list = await tenantDb.Queryable<SeaExport>().Where(x => x.SourceCode == "FOB-WSL" && SqlFunc.Between(x.ETD, startDate, endDate))
// .Select(x => new
// {
// x.Id,
// x.CustomerId,
// x.CustomerName,
// x.ETD,
// x.TEU
// }).ToListAsync();
// if (list.Count == 0)
// return;
// var ids = list.Select(x => x.Id.ToString());
// var ctnList = await tenantDb.Queryable<OpCtn>().Where(x => ids.Contains(x.BSNO) &&
// !SqlFunc.IsNullOrEmpty(x.CntrNo) && !SqlFunc.IsNullOrEmpty(x.SealNo))
// .Select(x => new
// {
// x.BSNO,
// x.TEU
// }).ToListAsync();
// model.List = list.GroupBy(x => new { x.CustomerId, x.CustomerName }).Select(x => new WSLItem
// {
// CustomerId = x.Key.CustomerId,
// CustomerName = x.Key.CustomerName,
// Date = model.Date,
// YesterdayTeu = x.Where(x => x.ETD >= yesterday0 && x.ETD <= yesterday).Sum(x => x.TEU),
// TodayTeu = x.Where(x => x.ETD >= today0 && x.ETD <= today).Sum(x => x.TEU),
// NextMonthTEU = x.Where(x => x.ETD.Value.Year == nextMonth.Year && x.ETD.Value.Month == nextMonth.Month).Sum(x => x.TEU),
// LastMonthTEU = x.Where(x => x.ETD.Value.Year == lastMonth.Year && x.ETD.Value.Month == lastMonth.Month).Sum(x => x.TEU),
// }).ToList();
// foreach (var item in model.List)
// {
// var ids2 = list.Where(x => x.CustomerId == item.CustomerId).Select(x => x.Id.ToString());
// item.TodayTeuCTNPickup = ctnList.Where(x => ids2.Contains(x.BSNO)).Sum(x => x.TEU);
// }
// MemoryStream ms = new MemoryStream();
// await MiniExcel.SaveAsByTemplateAsync(ms, path, model);
// string base64Str = Convert.ToBase64String(ms.ToArray());
// ms.Dispose();
// var attaches = new List<Attachment>
// {
// new() { AttachName = "WSL Volume Daily Increase Report.xlsx", AttachContent = base64Str}
// };
// dynamic[] mailParams = [new
// {
// SendTo = config["TaskMail:DefaultSetting:Receivers"],
// Title = "WSL Volume Daily Increase Report",
// Body = @"<article class='4ever-article'>
// <p style='line-height: 1;'>Dear WSL Team,</p>
// <p style='line-height: 1;'>Pls kindly check the daily report for your member's nomination booking:&nbsp;</p>
// <p style='line-height: 1;'>&nbsp;</p>
// <p style='line-height: 1;'>Thanks &amp; Best regards</p>
// <p style='line-height: 1;'>Candy SHAO 邵芳</p>
// <p style='line-height: 1;'>General Manager| <strong><span style='color: #e67e23;'>SUNNINESS LOGISTICS CO.,LTD.</span></strong></p>
// <p style='line-height: 1;'>TEL: +(86) (0532-80688387)1 MB./We chat: +(86)(18866622731) | QQ:2853083553|Email:candy@sunniness. net |WCA ID: 60272</p>
// </article>",
// Account = config["TaskMail:DefaultSetting:Account"],
// Password = config["TaskMail:DefaultSetting:Password"],
// Server = config["TaskMail:DefaultSetting:Host"],
// Port = config["TaskMail:DefaultSetting:Port"],
// UseSSL = config["TaskMail:DefaultSetting:UseSSL"],
// Attaches = attaches
// }];
// var mailResult = await api.SendRequestAsync(HttpMethod.Post, config["TaskMail:MailApiUrl"], mailParams);
// if (!mailResult.IsSuccessStatusCode)
// throw new ApplicationException("发送邮件失败");
// }
// }
// finally
// {
// tenantDb?.Dispose();
// }
// }
// class DefaultSetting
// {
// public long Tenant { get; set; }
// public string? Account { get; set; }
// public string? Password { get; set; }
// public string? Host { get; set; }
// public int? Port { get; set; }
// public bool UseSSL { get; set; }
// public string? Receivers { get; set; }
// }
// class Attachment
// {
// public string? AttachName { get; set; }
// public string? AttachContent { get; set; }
// }
// }
//}

@ -3,6 +3,7 @@ using DS.Module.Core;
using DS.WMS.Core.Sys.Entity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Quartz;
using SqlSugar;
@ -16,6 +17,7 @@ namespace DS.WMS.Core.QuarztJobs
static readonly ApiFox api;
ISqlSugarClient? db;
IConfiguration configuration;
ILogger<FeeCustTemplateJob> logger;
static FeeCustTemplateJob()
{
@ -30,6 +32,7 @@ namespace DS.WMS.Core.QuarztJobs
{
db = serviceProvider.GetRequiredService<ISqlSugarClient>();
configuration = serviceProvider.GetRequiredService<IConfiguration>();
logger = serviceProvider.GetRequiredService<ILogger<FeeCustTemplateJob>>();
}
/// <summary>
@ -39,12 +42,14 @@ namespace DS.WMS.Core.QuarztJobs
/// <returns></returns>
public async Task Execute(IJobExecutionContext context)
{
logger.LogInformation("开始运行【自动费用模板】生成...");
db.QueryFilter.Clear();
var dbLinks = await db.Queryable<Module.SqlSugar.SysTenantLink>().ToListAsync();
foreach (var dbLink in dbLinks)
{
if (configuration["AutoFeeTemplate:Tenant"] != dbLink.TenantId.ToString())
continue;
//if (configuration["AutoFeeTemplate:Tenant"] != dbLink.TenantId.ToString())
// continue;
var adminUser = await db.Queryable<SysUser>()
.Where(x => x.TenantId == dbLink.TenantId && x.Status == 0 && x.UserType == 1)
@ -62,7 +67,7 @@ namespace DS.WMS.Core.QuarztJobs
if (adminUser == null)
{
Console.WriteLine($"未能获取租户系统管理员租户ID{dbLink.TenantId}");
logger.LogInformation("未能获取租户系统管理员租户ID" + dbLink.TenantId);
continue;
}
@ -85,7 +90,10 @@ namespace DS.WMS.Core.QuarztJobs
{
var baseUrl = configuration["AutoFeeTemplate:BaseUrl"];
if (string.IsNullOrEmpty(baseUrl))
throw new ApplicationException("未配置自动费用模板请求基础URL");
{
logger.LogInformation("未配置自动费用模板请求基础URL");
return;
}
api.BaseUri = new Uri(baseUrl, UriKind.Absolute);
}
@ -96,8 +104,10 @@ namespace DS.WMS.Core.QuarztJobs
etd = DateTime.Now.Date
});
if (!response.IsSuccessStatusCode)
throw new ApplicationException("自动费用模板生成费用失败,详情查看日志");
if (response.IsSuccessStatusCode)
logger.LogInformation("【自动费用模板】生成完成...");
else
logger.LogInformation($"【自动费用模板】生成失败({response.ToString()}),详情查看日志!");
}
}
}

@ -4,6 +4,7 @@ using DS.WMS.Core.Info.Entity;
using DS.WMS.Core.Op.Entity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MiniExcelLibs;
using Quartz;
using SqlSugar;
@ -20,6 +21,7 @@ namespace DS.WMS.Core.QuarztJobs
ISqlSugarClient? db;
Microsoft.Extensions.Configuration.IConfiguration config;
IWebHostEnvironment hostEnvironment;
ILogger<WSLReportJob> logger;
static WSLReportJob()
{
@ -35,10 +37,13 @@ namespace DS.WMS.Core.QuarztJobs
db = serviceProvider.GetRequiredService<ISqlSugarClient>();
config = serviceProvider.GetRequiredService<Microsoft.Extensions.Configuration.IConfiguration>();
hostEnvironment = serviceProvider.GetRequiredService<IWebHostEnvironment>();
logger = serviceProvider.GetRequiredService<ILogger<WSLReportJob>>();
}
public async Task Execute(IJobExecutionContext context)
{
logger.LogInformation("开始生成【WSL报表服务】...");
string path = Path.Combine(hostEnvironment.WebRootPath, "templates", "WSL.xlsx");
FileInfo templateFile = new(path);
if (!templateFile.Exists)
@ -84,7 +89,7 @@ namespace DS.WMS.Core.QuarztJobs
};
var list = await tenantDb.Queryable<SeaExport>().Where(x => x.SourceCode == SOURCE_CODE && SqlFunc.Between(x.ETD, startDate, endDate) && !x.Deleted)
.InnerJoin<InfoClient>((x, y) => x.CustomerId == y.Id)
.LeftJoin<InfoClient>((x, y) => x.CustomerId == y.Id)
.Select((x, y) => new
{
x.Id,
@ -95,8 +100,11 @@ namespace DS.WMS.Core.QuarztJobs
}).ToListAsync();
if (list.Count == 0)
return;
{
model.List = [];
}
else
{
var ids = list.Select(x => x.Id.ToString());
var ctnList = await tenantDb.Queryable<OpCtn>().Where(x => ids.Contains(x.BSNO) &&
!SqlFunc.IsNullOrEmpty(x.CntrNo) && !SqlFunc.IsNullOrEmpty(x.SealNo) && !x.Deleted)
@ -122,6 +130,7 @@ namespace DS.WMS.Core.QuarztJobs
var ids2 = list.Where(x => x.CustomerId == item.CustomerId).Select(x => x.Id.ToString());
item.TodayTeuCTNPickup = ctnList.Where(x => ids2.Contains(x.BSNO)).Sum(x => x.TEU);
}
}
MemoryStream ms = new();
await MiniExcel.SaveAsByTemplateAsync(ms, path, model);
@ -147,8 +156,10 @@ namespace DS.WMS.Core.QuarztJobs
}];
var mailResult = await api.SendRequestAsync(HttpMethod.Post, config["TaskMail:MailApiUrl"], mailParams);
if (!mailResult.IsSuccessStatusCode)
throw new ApplicationException("发送邮件失败");
if (mailResult.IsSuccessStatusCode)
logger.LogInformation("已发送【WSL报表服务】...");
else
logger.LogInformation("发送【WSL报表服务】失败");
}
}
catch (Exception ex)

@ -16,7 +16,7 @@ using NLog.Web;
var builder = WebApplication.CreateBuilder(args);
var environment = builder.Environment.EnvironmentName;
Console.WriteLine("当前开发环境:" + environment);
Console.WriteLine("µ±Ç°»·¾³:" + environment);
//×¢²áÅäÖÃ
builder.Configuration
// .SetBasePath(builder.Environment.ContentRootPath)

@ -20,7 +20,7 @@ using DS.Module.QuartzModuleInstall;
var builder = WebApplication.CreateBuilder(args);
var environment = builder.Environment.EnvironmentName;
Console.WriteLine("当前开发环境:" + environment);
Console.WriteLine("µ±Ç°»·¾³:" + environment);
//×¢²áÅäÖÃ
builder.Configuration
// .SetBasePath(builder.Environment.ContentRootPath)

@ -148,6 +148,6 @@
"FileType": [ ".xls", ".xlsx" ]
},
"JobConfig": {
"WSLReportJob": "0 0 1 * * ?"
"WSLReportJob": "0 0 17 * * ?"
}
}

Loading…
Cancel
Save