HRM-10/HRM.UI/Controllers/CommonInterface/EmailLogController.cs

449 lines
18 KiB
C#
Raw Normal View History

2026-11-03 13:06:00 +06:00
using HRM.BO;
using HRM.BO.Configuration;
using HRM.DA;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
namespace HRM.UI.Controllers.CommonInterface
{
/// <summary>
/// Read side of the central email log, plus the generic retry.
///
/// Everything here works off MasterEmailLog.EmailType, so a new kind of mail
/// - Bonus Payslip, Tax Certificate, anything - shows up on this screen and
/// can be retried from it without a single change in this controller.
/// </summary>
[Route("api/emailLog")]
[ApiController]
[Authorize]
public class EmailLogController : ControllerBase
{
private readonly IMasterEmailLogService _masterEmailLogService;
private readonly IEmailDispatchService _emailDispatchService;
private readonly IOptions<EmailSettings> _emailSettings;
public EmailLogController(IMasterEmailLogService masterEmailLogService,
IEmailDispatchService emailDispatchService,
IOptions<EmailSettings> emailSettings)
{
this._masterEmailLogService = masterEmailLogService;
this._emailDispatchService = emailDispatchService;
this._emailSettings = emailSettings;
}
#region Batch list and detail
/// <summary>
/// History grid. emailType 0 means "every type"; the payroll type is
/// always taken from the caller's own token, never from the request.
/// </summary>
[HttpGet("getLogs/{emailType}/{fromDate}/{toDate}")]
public ActionResult GetLogs(int emailType, DateTime fromDate, DateTime toDate)
{
List<MasterEmailLog> items = new List<MasterEmailLog>();
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
items = _masterEmailLogService.Get((EnumEmailType)emailType, currentUser.PayrollTypeID, fromDate,
toDate);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
/// <summary>One batch header - what the progress panel polls while a run is going.</summary>
[HttpGet("getLog/{id}")]
public ActionResult GetLog(int id)
{
MasterEmailLog item = null;
try
{
item = _masterEmailLogService.Get(id);
if (item == null)
{
return NotFound(new { message = "Email log not found." });
}
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(item);
}
/// <summary>
/// Recipient rows of one batch. sendStatus 0 means "every status";
/// pass 3 to get exactly the people who need to be re-sent.
/// </summary>
[HttpGet("getLogDetails/{id}/{sendStatus}")]
public ActionResult GetLogDetails(int id, int sendStatus)
{
List<MasterEmailLogDetails> items = new List<MasterEmailLogDetails>();
try
{
items = sendStatus == 0
? _masterEmailLogService.GetDetails(id)
: _masterEmailLogService.GetDetails(id, (EnumEmailSendStatus)sendStatus);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
/// <summary>Every mail ever sent to one employee.</summary>
[HttpGet("getLogDetailsByEmployee/{employeeId}")]
public ActionResult GetLogDetailsByEmployee(int employeeId)
{
List<MasterEmailLogDetails> items = new List<MasterEmailLogDetails>();
try
{
items = _masterEmailLogService.GetDetailsByEmployee(employeeId);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
/// <summary>The file that was actually mailed to one recipient.</summary>
[HttpGet("downloadAttachment/{masterEmailLogId}/{detailId}")]
public ActionResult DownloadAttachment(int masterEmailLogId, int detailId)
{
try
{
// Per-recipient documents (payslip, tax card, tax certificate)
// are stored on the recipient's own row.
byte[] data = _masterEmailLogService.GetAttachment(detailId);
string fileName = null;
if (data == null || data.Length == 0)
{
// A batch where everyone got the SAME file keeps one copy on
// the header instead of a copy per recipient, so fall back
// to that before reporting there is nothing to download.
MasterEmailLog log = _masterEmailLogService.Get(masterEmailLogId);
EmailAttachmentInfo shared = ReadSharedAttachment(log);
if (shared != null)
{
data = shared.Data;
fileName = shared.FileName;
}
}
if (data == null || data.Length == 0)
{
return NotFound(new { message = "No attachment was kept for this recipient." });
}
return string.IsNullOrWhiteSpace(fileName)
? File(data, "application/octet-stream")
: File(data, "application/octet-stream", fileName);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
#endregion
#region Retry
/// <summary>
/// Re-sends only the Failed rows of a batch, using the file each row
/// already holds. Starts on its own thread and returns straight away,
/// exactly like the original send - the caller watches the batch header
/// for progress.
/// </summary>
[HttpPost("retryFailed/{id}")]
public ActionResult RetryFailed(int id)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
try
{
MasterEmailLog log = _masterEmailLogService.Get(id);
if (log == null)
{
return NotFound(new { message = "Email log not found." });
}
if (log.BatchStatus == EnumEmailBatchStatus.Processing)
{
return BadRequest(new { message = "This batch is still running. Please wait for it to finish." });
}
List<MasterEmailLogDetails> failed =
_masterEmailLogService.GetDetails(id, EnumEmailSendStatus.Failed);
if (failed.Count == 0)
{
return BadRequest(new { message = "There is no failed recipient to retry in this batch." });
}
EmailSettings emailSettings = _emailSettings.Value;
IEmailDispatchService dispatchService = _emailDispatchService;
int userID = currentUser.UserID;
// Payslips and tax documents carry their own stored bytes, so
// they need no resolver. A general mail (and a calendar schedule
// email) shares one file held on the header, which has to be
// handed back or the retry would go out without the attachment.
Func<MasterEmailLogDetails, EmailAttachmentInfo> resolver =
log.EmailType == EnumEmailType.GeneralMail || log.EmailType == EnumEmailType.ScheduleEmail
? BuildGeneralMailResolver(log)
: null;
EmailLogBackgroundRunner.Run(() =>
dispatchService.RetryFailed(id, emailSettings, userID, resolver));
return Ok(new
{
masterEmailLogID = id,
retryCount = failed.Count,
message = "Retry started for " + failed.Count + " recipient(s)."
});
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
#endregion
#region General mail
/// <summary>
/// Largest attachment a general mail may carry, before base64 encoding.
/// </summary>
private const int MaxGeneralAttachmentBytes = 10 * 1024 * 1024;
/// <summary>
/// Sends a free-form message - subject, body and one optional file the
/// operator picked - to many employees.
///
/// Unlike a payslip or a tax card, every recipient here gets the SAME
/// file, so it is stored once on the batch header (ParameterJson) rather
/// than copied onto all thousand recipient rows; a 5 MB attachment to
/// 1000 people would otherwise be 5 GB in MasterEmailLogDetails. Retry
/// reads it back from there - see BuildGeneralMailResolver.
/// </summary>
[HttpPost]
[Route("sendGeneralMail")]
public ActionResult SendGeneralMail(dynamic data)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser == null || currentUser.PayrollTypeID == null)
{
return Unauthorized(new { message = "A signed-in payroll user is required to send mail." });
}
try
{
var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data));
var employees = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data.list));
string subject = ReadOptionalText(item, "emailSubject");
string body = ReadOptionalText(item, "emailBody");
string attachmentName = ReadOptionalText(item, "attachmentName");
string attachmentBase64 = ReadOptionalText(item, "attachmentData");
if (string.IsNullOrWhiteSpace(subject))
{
return BadRequest(new { message = "Email subject is required." });
}
if (string.IsNullOrWhiteSpace(body))
{
return BadRequest(new { message = "Email body is required." });
}
byte[] attachmentBytes = null;
if (!string.IsNullOrWhiteSpace(attachmentBase64))
{
if (string.IsNullOrWhiteSpace(attachmentName))
{
return BadRequest(new { message = "The attachment has no file name." });
}
try
{
attachmentBytes = Convert.FromBase64String(attachmentBase64);
}
catch (FormatException)
{
return BadRequest(new { message = "The attachment could not be read. Please pick it again." });
}
if (attachmentBytes.Length > MaxGeneralAttachmentBytes)
{
return BadRequest(new
{
message = "The attachment is larger than "
+ (MaxGeneralAttachmentBytes / (1024 * 1024)) + " MB."
});
}
}
List<EmailRecipient> recipients = new List<EmailRecipient>();
foreach (var employee in employees)
{
EmailRecipient recipient = new EmailRecipient();
recipient.EmployeeID = Convert.ToInt32(employee.employeeID);
recipient.EmployeeNo = Convert.ToString(employee.employeeNo);
recipient.EmployeeName = Convert.ToString(employee.name);
recipient.MailTo = employee.employeeEmail == null
? string.Empty
: Convert.ToString(employee.employeeEmail);
recipient.Subject = subject;
recipient.Body = BuildGeneralMailBody(recipient.EmployeeName, body);
recipients.Add(recipient);
}
if (recipients.Count == 0)
{
return BadRequest(new { message = "No employee was selected." });
}
EmailDispatchRequest request = new EmailDispatchRequest();
request.EmailType = EnumEmailType.GeneralMail;
request.Description = subject.Length > 200 ? subject.Substring(0, 200) : subject;
request.PayrollTypeID = (int)currentUser.PayrollTypeID;
request.UserID = currentUser.UserID;
request.Recipients = recipients;
// The one shared copy of the file lives here. Not on the
// recipient rows - see the note on this endpoint.
request.ParameterJson = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
attachmentName = attachmentName,
attachmentData = attachmentBase64,
payrollTypeId = (int)currentUser.PayrollTypeID
});
request.PreserveAttachment = false;
if (attachmentBytes != null)
{
byte[] bytes = attachmentBytes;
string fileName = attachmentName;
request.AttachmentResolver = (EmailRecipient recipient) =>
new EmailAttachmentInfo(fileName, bytes);
}
int masterEmailLogID = _emailDispatchService.CreateBatch(request);
EmailSettings emailSettings = _emailSettings.Value;
IEmailDispatchService dispatchService = _emailDispatchService;
EmailLogBackgroundRunner.Run(() =>
dispatchService.ProcessBatch(masterEmailLogID, request, emailSettings));
return Ok(new
{
masterEmailLogID = masterEmailLogID,
totalCount = recipients.Count,
message = "Sending started for " + recipients.Count + " employee(s)."
});
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
#endregion
#region General mail helpers
/// <summary>
/// Rebuilds the shared attachment of a general mail batch from its
/// header, so a retry re-sends the same file instead of a bare message.
/// Returns null when the batch carried no attachment.
/// </summary>
private static Func<MasterEmailLogDetails, EmailAttachmentInfo> BuildGeneralMailResolver(MasterEmailLog log)
{
EmailAttachmentInfo shared = ReadSharedAttachment(log);
return shared == null ? (Func<MasterEmailLogDetails, EmailAttachmentInfo>)null
: ((MasterEmailLogDetails detail) => shared);
}
/// <summary>
/// The one file a whole batch shared, read back off its header. Used
/// both to re-attach it on a retry and to serve it from the recipient
/// list, where the row itself holds no bytes. Returns null when the
/// batch carried no attachment, or when the header cannot be read - an
/// unreadable header is not a reason to fail the caller.
/// </summary>
private static EmailAttachmentInfo ReadSharedAttachment(MasterEmailLog log)
{
if (log == null || string.IsNullOrWhiteSpace(log.ParameterJson))
{
return null;
}
try
{
var parameters = Newtonsoft.Json.JsonConvert.DeserializeObject<
Newtonsoft.Json.Linq.JObject>(log.ParameterJson);
string fileName = parameters.Value<string>("attachmentName");
string base64 = parameters.Value<string>("attachmentData");
if (string.IsNullOrWhiteSpace(base64) || string.IsNullOrWhiteSpace(fileName))
{
return null;
}
return new EmailAttachmentInfo(fileName, Convert.FromBase64String(base64));
}
catch (Exception)
{
return null;
}
}
private static string BuildGeneralMailBody(string employeeName, string operatorBody)
{
string message = string.IsNullOrWhiteSpace(operatorBody)
? string.Empty
: "<p>" + operatorBody.Trim() + "</p>";
return $@"<p>Dear {employeeName},</p>
{message}
<p>Best regards,<br/>HR Department</p>";
}
/// <summary>Reads an optional string field without throwing when it is absent.</summary>
private static string ReadOptionalText(dynamic item, string fieldName)
{
var field = item[fieldName];
return field == null ? string.Empty : (string)field.ToObject<string>();
}
#endregion
}
}