Utopia-Canteen-System/Services/EmployeeLookupService.cs

73 lines
2.7 KiB
C#

using MySqlConnector;
using UtopiaCanteenSystem.Models;
namespace UtopiaCanteenSystem.Services;
/// <summary>
/// Looks up employee from local HRMS MySQL: employee_rfid_tag.manufacturer_serial → employee (parent_document_id = serial_number) → department.
/// Uses IConfigService.GetHrmsLookupConnectionString(); separate from production sync connection.
/// </summary>
public class EmployeeLookupService : IEmployeeLookupService
{
private readonly IConfigService _configService;
public EmployeeLookupService(IConfigService configService)
{
_configService = configService;
}
/// <inheritdoc />
public async Task<HrmsEmployeeInfo?> GetEmployeeByRfidAsync(string rfid, CancellationToken cancellationToken = default)
{
var connectionString = _configService.GetHrmsLookupConnectionString();
if (string.IsNullOrWhiteSpace(connectionString))
return null;
const string sql = @"
SELECT
e.id AS parent_document_id,
e.serial_number AS employee_id,
e.concatenated_name AS first_name,
'' AS middle_name,
e.department_id,
d.title AS department_title,
d.department_type,
r.location_site_id AS location_site_id
FROM employee_rfid_tag r
JOIN employee e ON e.id = r.parent_document_id
LEFT JOIN department d ON d.id = e.department_id
WHERE r.manufacturer_serial = @rfid
AND r.parent_document_type = 'Employee'
LIMIT 1";
await using var conn = new MySqlConnection(connectionString);
await conn.OpenAsync(cancellationToken).ConfigureAwait(false);
await using var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@rfid", rfid?.Trim() ?? string.Empty);
await using var reader = await cmd.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
return null;
return new HrmsEmployeeInfo
{
ParentDocumentId = GetString(reader, 0),
EmployeeId = GetString(reader, 1),
FirstName = GetString(reader, 2),
MiddleName = GetString(reader, 3),
DepartmentId = GetString(reader, 4),
DepartmentTitle = GetString(reader, 5),
DepartmentType = GetString(reader, 6),
LocationSiteId = GetString(reader, 7)
};
}
private static string GetString(MySqlDataReader reader, int ordinal)
{
if (reader.IsDBNull(ordinal)) return string.Empty;
var v = reader.GetValue(ordinal);
return v?.ToString() ?? string.Empty;
}
}