using DS.Module.Core; using DS.WMS.Core.HangfireJob.Dtos; using DS.WMS.Core.Info.Entity; using DS.WMS.Core.Op.Entity; using DS.WMS.Core.QuarztJobs.Dtos; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using MiniExcelLibs; using Quartz; using SqlSugar; using System.Diagnostics.Contracts; using System.Globalization; using System.Threading; namespace DS.WMS.Core.QuarztJobs { /// /// WSL周报表服务 /// public class WSLWeeklyReportJob : IJob { const string SOURCE_CODE = "FOB-WSL"; static readonly ApiFox api; ISqlSugarClient? db; Microsoft.Extensions.Configuration.IConfiguration config; IWebHostEnvironment hostEnvironment; ILogger logger; static WSLWeeklyReportJob() { api = new ApiFox(); } /// /// 初始化 /// /// public WSLWeeklyReportJob(IServiceProvider serviceProvider) { db = serviceProvider.GetRequiredService(); config = serviceProvider.GetRequiredService(); hostEnvironment = serviceProvider.GetRequiredService(); logger = serviceProvider.GetRequiredService>(); } public async Task Execute(IJobExecutionContext context) { logger.LogInformation("开始生成【SUNNINESS-CARGOO REPORT报表服务】..."); string path = Path.Combine(hostEnvironment.WebRootPath, "templates", "CargooWeeklyReport.xlsx"); FileInfo templateFile = new(path); if (!templateFile.Exists) { var ex = new ApplicationException("【SUNNINESS-CARGOO REPORT报表服务】未能在下列路径找到模板文件:" + path); await ex.LogAsync(db); throw ex; } //时间计算 var today = DateTime.Now.Date; var yesterday = today.AddDays(-1).Date; var startDate = new DateTime(today.Year, today.Month, 1); var endDate = new DateTime(today.Year, today.Month,today.Day, 23, 59, 59); db.QueryFilter.Clear(); var dbLinks = await db.Queryable().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(); WSLWeeklyModel model = new() { Date = today.ToString("yyyy.MM.dd"), Month = today.ToString("yyyy.MM") }; var list = await tenantDb.Queryable().Where(x => !x.Deleted && x.IsChangeETD == false && x.IsRefund == false)//x.ContractClientName == "WSL" && && SqlFunc.Between(x.ETD, startDate, endDate) .OrderBy(x=>x.ETD) .Select(x => new WSLWeeklyItem() { BusinessStatusName = x.BusinessStatusName, Carrier = x.Carrier, Forwarder = x.Forwarder, ContractClientName = x.ContractClientName, ContractNo = x.ContractNo, MBLNO = x.MBLNO, CustomerNo = x.CustomerNo, ETD = x.ETD.HasValue ? x.ETD.Value.ToString("yyyy-MM-dd") : string.Empty, //Weeks = x.ETD.HasValue ? x.ETD.Value.GetWeekOfYear(CultureInfo.CurrentCulture), LoadPort = x.LoadPort, DischargePort = x.DischargePort, MBLFrt = x.MBLFrt, Sale = x.Sale, CustomerServiceName = x.CustomerServiceName, OperatorName = x.OperatorName, Laner = x.Laner, Vessel = x.Vessel, Voyno = x.Voyno, Shipper = x.Shipper, Consignee = x.Consignee, NotifyParty = x.NotifyParty, CreateTime = x.CreateTime.ToString("yyyy-MM-dd") }).ToListAsync(); model.List = list; MemoryStream ms = new(); await MiniExcel.SaveAsByTemplateAsync(ms, path, model); string base64Str = Convert.ToBase64String(ms.ToArray()); ms.Dispose(); var attaches = new List { 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("已发送【SUNNINESS-CARGOO REPORT报表服务】..."); else logger.LogInformation("发送【SUNNINESS-CARGOO REPORT报表服务】失败!"); } } catch (Exception ex) { await ex.LogAsync(db); } finally { tenantDb?.Dispose(); } } class Attachment { public string? AttachName { get; set; } public string? AttachContent { get; set; } } } }