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.

183 lines
7.7 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 DS.Module.Core;
using DS.WMS.Core.HangfireJob.Dtos;
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;
namespace DS.WMS.Core.QuarztJobs
{
/// <summary>
/// WSL报表服务
/// </summary>
public class WSLReportJob : IJob
{
const string SOURCE_CODE = "FOB-WSL";
static readonly ApiFox api;
ISqlSugarClient? db;
Microsoft.Extensions.Configuration.IConfiguration config;
IWebHostEnvironment hostEnvironment;
ILogger<WSLReportJob> logger;
static WSLReportJob()
{
api = new ApiFox();
}
/// <summary>
/// 初始化
/// </summary>
/// <param name="serviceProvider"></param>
public WSLReportJob(IServiceProvider serviceProvider)
{
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)
{
var ex = new ApplicationException("【WSL报表服务】未能在下列路径找到模板文件" + path);
await ex.LogAsync(db);
throw ex;
}
//时间计算
var today = DateTime.Now.Date;
var yesterday = today.AddDays(-1).Date;
var lastMonth = today.AddMonths(-1);
var nextMonth = today.AddMonths(1);
var startDate = new DateTime(lastMonth.Year, lastMonth.Month, 1);
var endDate = new DateTime(nextMonth.Year, nextMonth.Month, DateTime.DaysInMonth(nextMonth.Year, nextMonth.Month), 23, 59, 59);
db.QueryFilter.Clear();
var dbLinks = await db.Queryable<Module.SqlSugar.SysTenantLink>().ToListAsync();
SqlSugarClient? tenantDb = null;
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
});
tenantDb.QueryFilter.Clear();
WSLModel model = new()
{
Date = today.ToString("yyyy.MM.dd"),
Month = today.ToString("yyyy.MM")
};
var list = await tenantDb.Queryable<SeaExport>().Where(x => x.SourceCode == SOURCE_CODE && SqlFunc.Between(x.ETD, startDate, endDate) && !x.Deleted)
.LeftJoin<InfoClient>((x, y) => x.CustomerId == y.Id)
.Select((x, y) => new
{
x.Id,
x.CustomerId,
EnName = SqlFunc.IsNull(y.EnFullName, y.EnShortName),
x.ETD,
x.TEU
}).ToListAsync();
if (list.Count == 0)
{
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)
.Select(x => new
{
x.BSNO,
x.TEU
}).ToListAsync();
model.List = list.GroupBy(x => new { x.CustomerId, x.EnName }).Select(x => new WSLItem
{
CustomerId = x.Key.CustomerId,
CustomerName = x.Key.EnName,
Date = model.Date,
YesterdayTeu = x.Where(x => x.ETD >= yesterday && x.ETD <= yesterday).Sum(x => x.TEU),
TodayTeu = x.Where(x => x.ETD >= today && 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();
await MiniExcel.SaveAsByTemplateAsync(ms, path, model);
string base64Str = Convert.ToBase64String(ms.ToArray());
ms.Dispose();
var attaches = new List<Attachment>
{
new() { AttachName = config["TaskMail:DefaultSetting:Title"] + ".xlsx", AttachContent = base64Str}
};
dynamic[] mailParams = [new
{
SendTo = config["TaskMail:DefaultSetting:Receivers"],
CCTo = config["TaskMail:DefaultSetting:CCTo"],
Title = config["TaskMail:DefaultSetting:Title"],
Body = config["TaskMail:DefaultSetting:Body"],
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"]?.ToLowerInvariant(),
Attaches = attaches
}];
var mailResult = await api.SendRequestAsync(HttpMethod.Post, config["TaskMail:MailApiUrl"], mailParams);
if (mailResult.IsSuccessStatusCode)
logger.LogInformation("已发送【WSL报表服务】...");
else
logger.LogInformation("发送【WSL报表服务】失败");
}
}
catch (Exception ex)
{
await ex.LogAsync(db);
}
finally
{
tenantDb?.Dispose();
}
}
class Attachment
{
public string? AttachName { get; set; }
public string? AttachContent { get; set; }
}
}
}