HRM-10/HRM.DA/Service/Employee/EmpHistoricalDataService.cs
Mohaimen Hasan 838b8d4480 first commit
2026-11-03 13:06:00 +06:00

519 lines
22 KiB
C#

using Ease.Core.DataAccess;
using Ease.Core.Model;
using Ease.Core.Utility;
using HRM.BO;
using System;
using System.Collections.Generic;
namespace HRM.DA
{
/// <summary>
/// Serves the EmpHistoricalData holding table, which keeps the rows of the
/// "Historical Career Data Upload" Excel sheet as they were uploaded.
///
/// The department and location columns are not hardcoded: how many tiers there
/// are and what they are called comes from the Logic configuration
/// (department/tiernames, location/tiernames), the same source
/// getBasicInfoColumns uses for the System Opening Data upload. Configured
/// tier N is carried in the Nth fixed slot - Division, Department, Section,
/// SubSection for department and Location, SubLocation for location.
///
/// Nothing here reads or writes EmpLifeCycle or any payroll table, and the
/// Department and Location master tables are only ever read.
/// </summary>
public class EmpHistoricalDataService : ServiceTemplate, IEmpHistoricalDataService
{
#region Private functions and declaration
public EmpHistoricalDataService()
{
}
private void MapObject(EmpHistoricalData item, DataReader oReader)
{
base.SetObjectID(item, oReader.GetInt32("EmpHistoricalDataID").Value);
item.EmployeeID = oReader.GetInt32("EmployeeID");
item.EmployeeNo = oReader.GetString("EmployeeNo");
item.Name = oReader.GetString("Name");
item.EffectDate = oReader.GetDateTime("EffectDate");
item.EventType = oReader.GetString("EventType");
item.Designation = oReader.GetString("Designation");
item.EmployeeType = oReader.GetString("EmployeeType");
item.Division = oReader.GetString("Division");
item.Department = oReader.GetString("Department");
item.Section = oReader.GetString("Section");
item.SubSection = oReader.GetString("SubSection");
item.Grade = oReader.GetString("Grade");
item.CostCenter = oReader.GetString("CostCenter");
item.Location = oReader.GetString("Location");
item.SubLocation = oReader.GetString("SubLocation");
item.PFMember = oReader.GetString("PFMember");
item.BasicSalary = oReader.GetDouble("BasicSalary");
item.GrossSalary = oReader.GetDouble("GrossSalary");
item.PayrollTypeID = oReader.GetInt32("PayrollTypeID");
item.CreatedBy = oReader.GetInt32("CreatedBy", 0);
item.CreatedDate = oReader.GetDateTime("CreatedDate", DateTime.MinValue);
this.SetObjectState(item, Ease.Core.ObjectState.Saved);
}
protected override T CreateObject<T>(DataReader oReader)
{
EmpHistoricalData item = new EmpHistoricalData();
MapObject(item, oReader);
return item as T;
}
/// <summary>
/// EmployeeNo to EmployeeID for the given payroll type, read once per upload.
/// Used only to stamp a row with the employee it belongs to; an employee number
/// that does not match leaves EmployeeID null and the row is still saved as uploaded.
/// </summary>
private Dictionary<string, int> GetEmployeeIDsByNo(TransactionContext tc, int payrollTypeID)
{
Dictionary<string, int> empIDs = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
DataReader dr = new DataReader(EmpHistoricalDataDA.GetEmployeeNos(tc, payrollTypeID));
while (dr.Read())
{
string employeeNo = dr.GetString("EmployeeNo");
int? employeeID = dr.GetInt32("EmployeeID");
if (string.IsNullOrWhiteSpace(employeeNo) || employeeID == null) continue;
empIDs[employeeNo.Trim()] = employeeID.Value;
}
dr.Close();
return empIDs;
}
#endregion
#region Department / Location tiers from the Logic configuration
/// <summary>
/// Reads one tier list out of the Logic configuration exactly the way
/// getBasicInfoColumns does: every child of the given node whose Node is
/// "text", in configuration order, with its Value as the caption.
///
/// requireTierAttribute mirrors the reference uploader - it skips a "text"
/// row carrying no tier attribute for location, and keeps every row for
/// department.
/// </summary>
private List<EmpHistoricalDataTier> GetTiers(string parentNode, bool requireTierAttribute,
bool firstTierMandatoryOnly)
{
SystemConfigarationService ocManager = new SystemConfigarationService();
List<SystemConfigaration> config =
ocManager.GetAllChildrenByParentNode(EnumConfigurationType.Logic, parentNode);
List<EmpHistoricalDataTier> tiers = new List<EmpHistoricalDataTier>();
List<SystemConfigaration> texts = config.FindAll(x => x.Node == "text");
int nIndex = 0;
foreach (SystemConfigaration oconfig in texts)
{
if (requireTierAttribute && oconfig.ConAttributes.GetAttributeValue("tier") == "") continue;
nIndex = nIndex + 1;
tiers.Add(new EmpHistoricalDataTier
{
Tier = nIndex,
Name = oconfig.Value,
// Department marks only the first tier mandatory; location marks every tier.
IsMandatory = firstTierMandatoryOnly ? nIndex == 1 : true
});
}
return tiers;
}
/// <summary>
/// The department and location tiers the sheet must carry, straight from the
/// Logic configuration, so this screen and the System Opening Data upload stay
/// in step with one configuration.
/// </summary>
public EmpHistoricalDataColumnSetup GetColumnSetup()
{
EmpHistoricalDataColumnSetup setup = new EmpHistoricalDataColumnSetup();
try
{
SystemConfigarationService ocManager = new SystemConfigarationService();
setup.IsDepartmentCodeAutoGenerated =
ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "department", "codeautogenerate");
setup.IsLocationCodeAutoGenerated =
ocManager.GetconfigBooleanValue(EnumConfigurationType.Logic, "location", "codeautogenerate");
setup.DepartmentTiers = this.GetTiers("department", false, true);
setup.LocationTiers = this.GetTiers("location", true, false);
// EmpHistoricalData keeps one fixed slot per tier, so say plainly when the
// configuration asks for more tiers than there are slots.
setup.TierOverflowMessage =
DescribeOverflow(setup.DepartmentTiers, EmpHistoricalDataColumnSetup.MaxDepartmentTier,
"department") +
DescribeOverflow(setup.LocationTiers, EmpHistoricalDataColumnSetup.MaxLocationTier, "location");
if (setup.DepartmentTiers.Count > EmpHistoricalDataColumnSetup.MaxDepartmentTier)
setup.DepartmentTiers =
setup.DepartmentTiers.GetRange(0, EmpHistoricalDataColumnSetup.MaxDepartmentTier);
if (setup.LocationTiers.Count > EmpHistoricalDataColumnSetup.MaxLocationTier)
setup.LocationTiers =
setup.LocationTiers.GetRange(0, EmpHistoricalDataColumnSetup.MaxLocationTier);
}
catch (Exception e)
{
#region Handle Exception
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return setup;
}
private static string DescribeOverflow(List<EmpHistoricalDataTier> tiers, int maxTier, string what)
{
if (tiers.Count <= maxTier) return string.Empty;
string names = string.Empty;
for (int i = maxTier; i < tiers.Count; i++)
names += (names == string.Empty ? "" : ", ") + tiers[i].Name;
return "The Logic configuration has " + tiers.Count + " " + what + " tiers but this upload carries " +
maxTier + "; " + names + " cannot be uploaded here. ";
}
#endregion
#region Tier combination lookup
/// <summary>
/// The uploaded tier values of one row, tier 1 first, with the trailing blanks
/// removed so that the chain stops where the sheet stops.
/// </summary>
private static List<string> TierValues(EmpHistoricalData item, bool isDepartment, int tierCount)
{
List<string> values = new List<string>();
for (int tier = 1; tier <= tierCount; tier++)
{
string value = isDepartment ? GetDepartmentSlot(item, tier) : GetLocationSlot(item, tier);
values.Add(value == null ? string.Empty : value.Trim());
}
return values;
}
/// <summary>Configured department tier N is carried in the Nth fixed slot.</summary>
private static string GetDepartmentSlot(EmpHistoricalData item, int tier)
{
switch (tier)
{
case 1: return item.Division;
case 2: return item.Department;
case 3: return item.Section;
case 4: return item.SubSection;
default: return string.Empty;
}
}
/// <summary>Configured location tier N is carried in the Nth fixed slot.</summary>
private static string GetLocationSlot(EmpHistoricalData item, int tier)
{
switch (tier)
{
case 1: return item.Location;
case 2: return item.SubLocation;
default: return string.Empty;
}
}
/// <summary>
/// Walks the uploaded department chain against the Department master the way
/// ProcessBasicData does - tier 1 matched on its own, each deeper tier matched
/// only within the parent the tier above resolved to - and reports the first
/// tier value that has no match.
///
/// Read-only: unlike the reference uploader this never inserts a Department,
/// so a historical department that no longer exists simply does not resolve.
/// The uploaded text is kept either way.
/// </summary>
private static string FindUnresolvedDepartmentTier(List<Department> departments, List<string> values)
{
int parentID = 0;
for (int i = 0; i < values.Count; i++)
{
// Trim here too, so the walk does not depend on the caller having done it.
string value = values[i] == null ? string.Empty : values[i].Trim();
if (value == string.Empty) continue;
int tier = i + 1;
Department found = departments.Find(delegate(Department d)
{
if (!Matches(d.Name, d.Code, value) || d.Tier != tier) return false;
return tier == 1 || d.ParentID.GetValueOrDefault() == parentID;
});
if (found == null) return value;
parentID = found.ID;
}
return string.Empty;
}
/// <summary>Same walk as FindUnresolvedDepartmentTier, against the Location master.</summary>
private static string FindUnresolvedLocationTier(List<Location> locations, List<string> values)
{
int parentID = 0;
for (int i = 0; i < values.Count; i++)
{
// Trim here too, so the walk does not depend on the caller having done it.
string value = values[i] == null ? string.Empty : values[i].Trim();
if (value == string.Empty) continue;
int tier = i + 1;
Location found = locations.Find(delegate(Location l)
{
if (!Matches(l.Name, l.Code, value) || l.Tier != tier) return false;
return tier == 1 || l.ParentID.GetValueOrDefault() == parentID;
});
if (found == null) return value;
parentID = found.ID;
}
return string.Empty;
}
/// <summary>
/// EmpHistoricalData carries one column per tier, so a sheet may name a tier by
/// its description or by its code. Either is accepted, which cannot produce a
/// false mismatch whichever way the client fills the sheet in.
/// </summary>
private static bool Matches(string name, string code, string value)
{
return string.Equals(name == null ? "" : name.Trim(), value, StringComparison.OrdinalIgnoreCase)
|| string.Equals(code == null ? "" : code.Trim(), value, StringComparison.OrdinalIgnoreCase);
}
#endregion
#region Service implementation
public List<EmpHistoricalData> Get(int payrollTypeID)
{
List<EmpHistoricalData> items = new List<EmpHistoricalData>();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
DataReader dr = new DataReader(EmpHistoricalDataDA.Get(tc, payrollTypeID));
items = this.CreateObjects<EmpHistoricalData>(dr);
dr.Close();
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return items;
}
public EmpHistoricalData Get(int id, int payrollTypeID)
{
EmpHistoricalData item = null;
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
DataReader dr = new DataReader(EmpHistoricalDataDA.Get(tc, id, payrollTypeID));
if (dr.Read())
{
item = new EmpHistoricalData();
MapObject(item, dr);
}
dr.Close();
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return item;
}
/// <summary>
/// Appends the uploaded rows. Every row is inserted as given: historical data may
/// legitimately repeat the same employee, date or event, so nothing is merged,
/// skipped or overwritten here.
///
/// The tier captions are re-read from the Logic configuration here rather than
/// trusted from the browser, the same way regularExcelInterface re-reads the
/// column definition before importing.
/// </summary>
public List<UploadErrorOrSuccess> Save(List<EmpHistoricalData> items, int payrollTypeID, int userID)
{
if (items == null || items.Count == 0)
throw new ServiceException("No historical career data to upload.");
EmpHistoricalDataColumnSetup setup = this.GetColumnSetup();
List<Department> departments = new DepartmentService().Get(EnumStatus.Regardless, payrollTypeID);
List<Location> locations = new LocationService().Get(EnumStatus.Regardless, payrollTypeID);
List<UploadErrorOrSuccess> unmatched = new List<UploadErrorOrSuccess>();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin(true);
Dictionary<string, int> empIDs = this.GetEmployeeIDsByNo(tc, payrollTypeID);
int id = tc.GenerateID("EmpHistoricalData", "EmpHistoricalDataID");
int nRow = 0;
foreach (EmpHistoricalData item in items)
{
base.SetObjectID(item, id);
item.PayrollTypeID = payrollTypeID;
item.CreatedBy = userID;
item.CreatedDate = DateTime.Now;
int employeeID;
item.EmployeeID = !string.IsNullOrWhiteSpace(item.EmployeeNo) &&
empIDs.TryGetValue(item.EmployeeNo.Trim(), out employeeID)
? employeeID
: (int?)null;
// Clear any slot the configuration does not define a tier for, so a
// sheet can never smuggle a value into an unused slot.
this.ClearUnconfiguredSlots(item, setup);
this.CheckTierCombinations(item, setup, departments, locations, nRow, unmatched);
EmpHistoricalDataDA.Insert(tc, item);
id++;
nRow++;
}
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return unmatched;
}
/// <summary>
/// Walks the row's department and location tier chains against the master data
/// and records the ones that do not resolve. Reporting only - the row is saved
/// regardless, because historical data may name a department or location that
/// has since been removed.
/// </summary>
private void CheckTierCombinations(EmpHistoricalData item, EmpHistoricalDataColumnSetup setup,
List<Department> departments, List<Location> locations, int nRow, List<UploadErrorOrSuccess> unmatched)
{
List<string> deptValues = TierValues(item, true, setup.DepartmentTiers.Count);
string unresolvedDept = FindUnresolvedDepartmentTier(departments, deptValues);
if (unresolvedDept != string.Empty)
{
unmatched.Add(UploadErrorOrSuccess.Create(DescribeChain(setup.DepartmentTiers, deptValues), nRow,
"No matching department for '" + unresolvedDept + "' in this combination. The row is saved, but it does not tie to an existing department.",
item.EmployeeNo, item.Name));
}
List<string> locValues = TierValues(item, false, setup.LocationTiers.Count);
string unresolvedLoc = FindUnresolvedLocationTier(locations, locValues);
if (unresolvedLoc != string.Empty)
{
unmatched.Add(UploadErrorOrSuccess.Create(DescribeChain(setup.LocationTiers, locValues), nRow,
"No matching location for '" + unresolvedLoc + "' in this combination. The row is saved, but it does not tie to an existing location.",
item.EmployeeNo, item.Name));
}
}
/// <summary>"Division > Department > Section", using the configured captions.</summary>
private static string DescribeChain(List<EmpHistoricalDataTier> tiers, List<string> values)
{
string chain = string.Empty;
for (int i = 0; i < tiers.Count && i < values.Count; i++)
{
if (values[i] == string.Empty) continue;
chain += (chain == string.Empty ? "" : " > ") + tiers[i].Name;
}
return chain;
}
/// <summary>
/// Blanks the department/location slots beyond the configured tier count. With
/// three configured department tiers, for example, SubSection is not a column on
/// the sheet, so it must not hold a value.
/// </summary>
private void ClearUnconfiguredSlots(EmpHistoricalData item, EmpHistoricalDataColumnSetup setup)
{
int deptTiers = setup.DepartmentTiers.Count;
if (deptTiers < 4) item.SubSection = string.Empty;
if (deptTiers < 3) item.Section = string.Empty;
if (deptTiers < 2) item.Department = string.Empty;
if (deptTiers < 1) item.Division = string.Empty;
int locTiers = setup.LocationTiers.Count;
if (locTiers < 2) item.SubLocation = string.Empty;
if (locTiers < 1) item.Location = string.Empty;
}
/// <summary>
/// Deletes exactly one uploaded historical row, by its own key. Nothing else is
/// touched: employee master data, EmpLifeCycle and payroll data are not involved.
/// </summary>
public void Delete(int id, int payrollTypeID)
{
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin(true);
DataReader dr = new DataReader(EmpHistoricalDataDA.Get(tc, id, payrollTypeID));
bool exists = dr.Read();
dr.Close();
if (!exists)
throw new ServiceException(
"The historical career record was not found. It may already have been deleted.");
EmpHistoricalDataDA.Delete(tc, id, payrollTypeID);
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
#endregion
}
}