HRM-10/HRM.DA/Service/Users/UserRoleService.cs
2026-11-17 13:01:32 +06:00

1099 lines
40 KiB
C#

using Ease.Core.DataAccess;
using Ease.Core.Model;
using Ease.Core.Utility;
using HRM.BO;
using HRM.BO.Configuration;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
namespace HRM.DA
{
public class UserRoleService : ServiceTemplate, IUserRoleService
{
public UserRoleService()
{
}
private void MapObject(UserRole oUserRole, DataReader oReader)
{
base.SetObjectID(oUserRole, oReader.GetInt32("UserRoleID", 0));
oUserRole.RoleID = oReader.GetInt32("RoleID").Value;
oUserRole.UserID = oReader.GetInt32("UserID", 0);
oUserRole.EventDate = oReader.GetDateTime("EventDate").Value;
oUserRole.CreatedBy = oReader.GetInt32("CreatedBy", 0);
oUserRole.AuthorizedBy = oReader.GetInt32("AuthorizedBy", 0);
oUserRole.AuthorizedDate = oReader.GetDateTime("AuthorizedDate");
oUserRole.Status = (EnumStatus)oReader.GetInt32("Status").Value;
oUserRole.ComputerName = oReader.GetString("ComputerName");
oUserRole.ApprovedComputerName = oReader.GetString("ApprovedComputerName");
oUserRole.UserRoleStatus = (EnumAuthStatus)oReader.GetInt32("Status").Value;
oUserRole.employeeID = oReader.GetInt32("employeeID",true, 0) ==0? null: oReader.GetInt32("employeeID");
// Only the list query (UserRoleDA.Get by role type) carries EmpPayrollTypeID: the employee's payroll type.
int empPayrollTypeID = oReader.GetInt32("EmpPayrollTypeID", true, 0);
oUserRole.payrollTypeID = empPayrollTypeID == 0 ? null : empPayrollTypeID;
oUserRole.loginIDView = oReader.GetString("LoginID", true, string.Empty);
oUserRole.userNameView = oReader.GetString("userName", true, string.Empty);
oUserRole.roleNameView = oReader.GetString("roleName", true, string.Empty);
this.SetObjectState(oUserRole, Ease.Core.ObjectState.Saved);
}
protected override T CreateObject<T>(DataReader oReader)
{
UserRole oUserRole = new UserRole();
MapObject(oUserRole, oReader);
return oUserRole as T;
}
#region Service implementation
public UserRole Get(int id)
{
UserRole oUserRole = null;
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
DataReader oreader = new DataReader(UserRoleDA.Get(tc, id));
if (oreader.Read())
{
oUserRole = this.CreateObject<UserRole>(oreader);
}
oreader.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 oUserRole;
}
public List<UserRole> Get(EnumRoleType roleType, int? userid, int? RoleID)
{
List<UserRole> userRoles = new List<UserRole>();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
DataReader dr = new DataReader(UserRoleDA.Get(tc, roleType, userid, RoleID));
userRoles = this.CreateObjects<UserRole>(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 userRoles;
}
public List<UserRole> Get(List<SearchEmployee> searchEmps)
{
List<UserRole> userRoles = new List<UserRole>();
string insQL = "";
searchEmps.ForEach(x => { insQL = insQL + x.EmployeeID + ", "; });
if (insQL.Length > 2)
{
insQL = insQL.Substring(0, insQL.Length - 2);
}
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
DataReader dr = new DataReader(UserRoleDA.getAllByUserEMpNo(tc, insQL));
userRoles = this.CreateObjects<UserRole>(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 userRoles;
}
public List<UserRole> GetByUserID(int UserID)
{
List<UserRole> userRoles = new List<UserRole>();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
DataReader dr = new DataReader(UserRoleDA.GetByUserID(tc, UserID));
userRoles = this.CreateObjects<UserRole>(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
}
#endregion
return userRoles;
}
public int Save(UserRole oUserRole)
{
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin(true);
if (oUserRole.IsNew)
{
int id = tc.GenerateID("UserRole", "UserRoleID");
base.SetObjectID(oUserRole, id);
UserRoleDA.Insert(tc, oUserRole);
}
else
{
UserRoleDA.Update(tc, oUserRole);
}
tc.End();
return oUserRole.ID;
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
//public void SaveSingleUserRole(UserRole oUserRole)
//{
// TransactionContext tc = null;
// try
// {
// tc = TransactionContext.Begin(true);
// int id = tc.GenerateID("UserRole", "UserRoleID");
// oUserRole.SetObjectID(id);
// UserRoleDA.Insert(tc, oUserRole);
// tc.End();
// }
// catch (Exception e)
// {
// #region Handle Exception
// if (tc != null)
// tc.HandleError();
// ExceptionLog.Write(e);
// throw new ServiceException(e.Message, e);
// #endregion
// }
//}
//public void DeleteByUserID2(int id)
//{
// TransactionContext tc = null;
// try
// {
// tc = TransactionContext.Begin(true);
// this.DeleteByUserID(tc, id);
// tc.End();
// }
// catch (Exception e)
// {
// #region Handle Exception
// if (tc != null)
// tc.HandleError();
// ExceptionLog.Write(e);
// throw new ServiceException(e.Message, e);
// #endregion
// }
//}
private string MakePassWord(DateTime birthdate)
{
string password = String.Empty;
int year = birthdate.Year;
int month = birthdate.Month;
int day = birthdate.Day;
string emonth;
if (month < 10) emonth = "0" + month.ToString();
else emonth = month.ToString();
string eday;
if (day < 10) eday = "0" + day.ToString();
else eday = day.ToString();
password = year.ToString() + emonth + eday;
return password;
}
public void Save(List<UserRole> oUserRoles, int parentUserID)
{
TransactionContext tc = null;
try
{
List<Employee> oemps = new List<Employee>();
List<User> oUsers = new List<User>();
List<UserRole> PreviousRoles = new List<UserRole>();
if (oUserRoles[0].UserID == 0)
{
string empIn = "";
oUserRoles.ForEach(x => { empIn = empIn + x.employeeID + ", "; });
empIn = empIn.Substring(0, empIn.Length - 2);
EmployeeService empService = new EmployeeService();
tc = TransactionContext.Begin();
DataReader dr = new DataReader(UserRoleDA.getAllByUserEMpNo(tc, empIn));
PreviousRoles = this.CreateObjects<UserRole>(dr);
dr.Close();
tc.End();
foreach(UserRole prvUser in PreviousRoles)
{
oUserRoles.ForEach(u => {
if(u.employeeID == prvUser.employeeID)
u.UserID = prvUser.UserID;
});
//oUserRoles.ForEach(u => {
// if (u.UserID == prvUser.UserID && u.RoleID == prvUser.RoleID)
// u.ID = prvUser.ID;
//});
}
empIn = "";
oUserRoles.ForEach(x =>
{
if (x.UserID == 0)
empIn = empIn + x.employeeID + ", ";
});
if (empIn.Length > 0)
{
empIn = empIn.Substring(0, empIn.Length - 2);
oemps = empService.GetByEmpIDs(empIn, (int)oUserRoles[0].payrollTypeID);
foreach (Employee emp in oemps)
{
User userObject = new User();
userObject.LoginID = emp.EmployeeNo;
userObject.UserName = emp.Name;
userObject.Password = MakePassWord(emp.BirthDate);
userObject.ParentID = parentUserID;
userObject.PasswordHints = MakePassWord(emp.BirthDate);
userObject.EmployeeID = emp.ID;
// the employee's e-mail becomes the user's (both e-mail columns); no e-mail on the employee leaves them empty
userObject.Email = string.IsNullOrWhiteSpace(emp.EmailAddress) ? null : emp.EmailAddress.Trim();
// userObject.EmailAddress = userObject.Email;
userObject.UserStatus = EnumAuthStatus.Approved;
userObject.ChangePasswordAtNextLogon = true;
userObject.SISU = false;
userObject.CreatedDate = DateTime.Now;
userObject.UserType = EnumUserType.Employee;
oUsers.Add(userObject);
}
}
}
tc = TransactionContext.Begin(true);
foreach (User ouser in oUsers)
{
UserService oUService = new UserService();
int ID = oUService.Save(tc, ouser);
oUserRoles.ForEach(x => {
if(x.loginIDView == ouser.LoginID)
x.UserID = ID;
});
}
var usersids = oUserRoles.GroupBy(x => x.UserID).ToList();
usersids.ForEach(x =>{
this.DeleteByUserID(tc, x.Key);
});
int id = tc.GenerateID("UserRole", "UserRoleID");
foreach (UserRole userRole in oUserRoles)
{
this.Save(tc, userRole, id);
id = id + 1;
}
tc.End();
// net
EmailSettings st = new EmailSettings();
MailSender sender = null;
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
IConfiguration Configuration = builder.Build();
Configuration.GetSection("EmailSettings").Bind(st);
sender = new MailSender();
foreach (Employee emp in oemps)
{
if (emp.EmailAddress != "")
{
EmailSettings emailSettings = st;
string password = MakePassWord(emp.BirthDate);
MailSender mailSender = new MailSender();
mailSender.AddTo(emp.EmailAddress);
mailSender.Subject = "Your HR software Login information";
mailSender.Body = @"Your HR software Login information are following.
<p> <b>Log-in ID : </b> " + emp.EmployeeNo + "</p>";
mailSender.Body += "<p> <b>Password : </b> " + password.Trim() + "</p>";
mailSender.ThreadSendMail(emailSettings);
}
}
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
//public void Update(List<UserRole> oUserRoles)
//{
// TransactionContext tc = null;
// try
// {
// tc = TransactionContext.Begin(true);
// //this.DeleteByUserID(tc,oUserRoles[0].UserID);
// foreach (UserRole userRole in oUserRoles)
// {
// this.Save3(tc, userRole);
// }
// tc.End();
// }
// catch (Exception e)
// {
// #region Handle Exception
// if (tc != null)
// tc.HandleError();
// ExceptionLog.Write(e);
// throw new ServiceException(e.Message, e);
// #endregion
// }
//}
#region Maker-checker (Authentication > User Role Permission)
// UserRole.Status (UserRoleMakerChecker_DB_Changes.sql): Approved (5) = live; NewNotYetApprove (2) =
// given, not live until approved; DeletedNotYetApprove (3) = being taken away, still live until approved.
private static bool IsSelfService(UserRoleSubject subject)
{
return subject.RoleType == EnumRoleType.Self_Service;
}
private static bool IsPendingStatus(EnumAuthStatus status)
{
return status == EnumAuthStatus.NewNotYetApprove || status == EnumAuthStatus.DeletedNotYetApprove;
}
// The Self Service employee's login, if there is one: by EmployeeID first, then by
// LoginID = EmployeeNo (how older employee logins were made).
private User FindEmployeeLogin(int employeeID, string employeeNo)
{
UserService userService = new UserService();
User user = userService.Get(employeeID, EnumUserType.Employee);
if (user == null && !string.IsNullOrWhiteSpace(employeeNo))
{
User byLogin = userService.Get(employeeNo);
if (byLogin != null && byLogin.UserType == EnumUserType.Employee)
user = byLogin;
}
return user;
}
// UserRole rows as the maker-checker screens show them. A row waiting for approval becomes a request:
// Status 2 = give the role (maker CreatedBy, asked on EventDate), Status 3 = take it away (maker
// ModifiedBy, asked on ModifiedDate).
private List<UserRoleRequest> ReadRows(TransactionContext tc, bool pendingOnly, int? userID, EnumRoleType? roleType)
{
List<UserRoleRequest> items = new List<UserRoleRequest>();
DataReader dr = new DataReader(UserRoleDA.GetForMakerChecker(tc, pendingOnly, userID, roleType));
while (dr.Read())
{
UserRoleRequest item = new UserRoleRequest();
base.SetObjectID(item, dr.GetInt32("UserRoleID", 0));
item.Status = (EnumAuthStatus)dr.GetInt32("Status", (int)EnumAuthStatus.Approved);
bool isRemoval = item.Status == EnumAuthStatus.DeletedNotYetApprove;
item.RequestType = isRemoval ? EnumUserRoleRequestType.Remove : EnumUserRoleRequestType.Add;
item.RoleID = dr.GetInt32("RoleID", 0);
item.RoleType = (EnumRoleType)dr.GetInt32("RoleType", 0);
item.UserID = dr.GetInt32("UserID");
item.EmployeeID = dr.GetInt32("EmployeeID");
item.PayrollTypeID = dr.GetInt32("PayrollTypeID");
item.CreatedBy = isRemoval ? dr.GetInt32("ModifiedBy", 0) : dr.GetInt32("CreatedBy", 0);
item.CreatedDate = isRemoval
? dr.GetDateTime("ModifiedDate", DateTime.MinValue)
: dr.GetDateTime("EventDate", DateTime.MinValue);
item.RoleName = dr.GetString("RoleName");
item.LoginID = dr.GetString("LoginID");
item.PersonName = dr.GetString("PersonName");
item.EmployeeNo = dr.GetString("EmployeeNo");
item.MakerLoginID = dr.GetString("MakerLoginID");
this.SetObjectState(item, Ease.Core.ObjectState.Saved);
items.Add(item);
}
dr.Close();
return items;
}
public UserRoleState GetRoleState(UserRoleSubject subject)
{
UserRoleState state = new UserRoleState();
state.RoleType = subject.RoleType;
try
{
User login = null;
if (IsSelfService(subject))
{
int employeeID = subject.EmployeeID ?? 0;
if (employeeID <= 0 && (subject.UserID ?? 0) > 0)
employeeID = new UserService().Get(subject.UserID.Value)?.EmployeeID ?? 0;
Employee emp = new EmployeeService().Get(employeeID);
if (emp == null || emp.ID <= 0)
throw new InvalidOperationException("Employee not found.");
state.EmployeeID = emp.ID;
state.PayrollTypeID = emp.PayrollTypeID;
state.PersonName = emp.Name;
state.LoginID = emp.EmployeeNo;
login = FindEmployeeLogin(emp.ID, emp.EmployeeNo);
}
else
{
login = new UserService().Get(subject.UserID ?? 0);
if (login == null)
throw new InvalidOperationException("User not found.");
state.PersonName = login.UserName;
}
if (login != null)
{
state.UserID = login.ID;
state.LoginID = login.LoginID;
state.HasLogin = true;
state.LoginWaiting = login.UserStatus == EnumAuthStatus.NewNotYetApprove;
}
if (state.HasLogin)
{
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
List<UserRoleRequest> rows = ReadRows(tc, false, state.UserID, subject.RoleType);
tc.End();
state.LiveRoleIDs = rows.Where(r => r.Status != EnumAuthStatus.NewNotYetApprove)
.Select(r => r.RoleID).Distinct().ToList();
state.Pending = rows.Where(r => IsPendingStatus(r.Status)).ToList();
}
catch
{
if (tc != null)
tc.HandleError();
throw;
}
}
}
catch (Exception e)
{
#region Handle Exception
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return state;
}
public int RequestChange(UserRoleChangeRequest request, int makerID)
{
TransactionContext tc = null;
int changed = 0;
try
{
UserRoleState state = this.GetRoleState(request);
if (state.Pending.Count > 0)
throw new InvalidOperationException("This person already has a role change waiting for approval.");
List<int> live = state.LiveRoleIDs;
List<int> wanted = (request.RoleIDs ?? new List<int>()).Distinct().ToList();
List<int> adds = wanted.Where(r => !live.Contains(r)).ToList();
List<int> removes = live.Where(r => !wanted.Contains(r)).ToList();
if (adds.Count == 0 && removes.Count == 0)
return 0;
// A Self Service employee with no login gets one now, switched off (Status 2) until approved.
User newLogin = null;
if (IsSelfService(request) && !state.HasLogin)
{
Employee emp = new EmployeeService()
.GetByEmpIDs(state.EmployeeID.ToString(), request.PayrollTypeID ?? 0).FirstOrDefault();
if (emp == null)
throw new InvalidOperationException("Employee not found in the selected payroll type.");
newLogin = this.NewEmployeeLogin(emp, makerID);
}
DateTime now = DateTime.Now;
tc = TransactionContext.Begin(true);
int userID = state.UserID ?? 0;
if (newLogin != null)
userID = new UserService().Save(tc, newLogin);
foreach (int roleID in adds)
{
UserRoleDA.InsertPending(tc, tc.GenerateID("UserRole", "UserRoleID"), roleID, userID, makerID, now);
changed++;
}
if (removes.Count > 0)
{
// One row at a time (see UserRoleDA): every live row of each role being taken away.
foreach (UserRoleRequest row in ReadRows(tc, false, userID, request.RoleType)
.Where(r => r.Status != EnumAuthStatus.NewNotYetApprove && removes.Contains(r.RoleID)))
{
UserRoleDA.RequestRemoval(tc, row.ID, makerID, now);
}
changed += removes.Count;
}
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return changed;
}
public void Approve(UserRoleSubject subject, int approverID)
{
TransactionContext tc = null;
Employee loginToMail = null;
try
{
UserRoleState state = this.GetRoleState(subject);
if (state.Pending.Count == 0)
throw new InvalidOperationException("No role change is waiting for approval.");
int userID = state.UserID.Value;
// A login made by the maker for a Self Service employee is switched on now, and mailed as before.
if (IsSelfService(subject) && state.LoginWaiting)
{
loginToMail = new EmployeeService().Get(state.EmployeeID ?? 0);
}
int? notifyEmployeeID = IsSelfService(subject) ? state.EmployeeID : new UserService().Get(userID)?.EmployeeID;
DateTime now = DateTime.Now;
tc = TransactionContext.Begin(true);
// One row at a time (see UserRoleDA): removals go, given roles become live.
foreach (UserRoleRequest row in state.Pending)
{
if (row.RequestType == EnumUserRoleRequestType.Remove)
UserRoleDA.DeleteRow(tc, row.ID);
else
UserRoleDA.ApproveRow(tc, row.ID, approverID, now);
}
if (loginToMail != null)
UserDA.UpdateStatus(tc, userID, EnumAuthStatus.Approved, approverID, now);
foreach (UserRoleRequest req in state.Pending.Where(p => p.RequestType == EnumUserRoleRequestType.Add))
this.NotifyRoleGranted(tc, subject.RoleType, notifyEmployeeID, req.RoleName, req.ID, approverID);
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
if (loginToMail != null && loginToMail.ID > 0)
this.MailNewLogin(new List<Employee> { loginToMail });
}
public void Reject(UserRoleSubject subject, int approverID)
{
TransactionContext tc = null;
try
{
UserRoleState state = this.GetRoleState(subject);
if (state.Pending.Count == 0)
throw new InvalidOperationException("No role change is waiting for approval.");
int userID = state.UserID.Value;
tc = TransactionContext.Begin(true);
// One row at a time (see UserRoleDA): given roles go, removals stay live.
foreach (UserRoleRequest row in state.Pending)
{
if (row.RequestType == EnumUserRoleRequestType.Remove)
UserRoleDA.RestoreRow(tc, row.ID);
else
UserRoleDA.DeleteRow(tc, row.ID);
}
// A login the maker made for this change, never switched on and now without any role, goes too.
if (IsSelfService(subject) && state.LoginWaiting && UserRoleDA.CountByUser(tc, userID) == 0)
UserDA.Delete(tc, userID);
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
public List<UserRoleRequest> GetPending()
{
List<UserRoleRequest> items = new List<UserRoleRequest>();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
items = ReadRows(tc, true, null, null);
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;
}
// The employee login the old Save created (same values), but switched off (Status 2) until the
// role change is approved.
private User NewEmployeeLogin(Employee emp, int parentUserID)
{
User userObject = new User();
userObject.LoginID = emp.EmployeeNo;
userObject.UserName = emp.Name;
userObject.Password = MakePassWord(emp.BirthDate);
userObject.ParentID = parentUserID;
userObject.PasswordHints = MakePassWord(emp.BirthDate);
userObject.EmployeeID = emp.ID;
userObject.Email = string.IsNullOrWhiteSpace(emp.EmailAddress) ? null : emp.EmailAddress.Trim();
userObject.UserStatus = EnumAuthStatus.NewNotYetApprove;
userObject.ChangePasswordAtNextLogon = true;
userObject.SISU = false;
userObject.CreatedDate = DateTime.Now;
userObject.UserType = EnumUserType.Employee;
return userObject;
}
// The "role assigned" notification the old Save sent, now sent when the role is really live.
private void NotifyRoleGranted(TransactionContext tc, EnumRoleType roleType, int? employeeID, string roleName,
int userRoleID, int approverID)
{
if (!employeeID.HasValue || (roleType != EnumRoleType.Self_Service && roleType != EnumRoleType.Admin))
return;
bool hasRoleName = !string.IsNullOrWhiteSpace(roleName);
string description = roleType == EnumRoleType.Admin
? (hasRoleName ? $"You have been granted Admin access with the role: {roleName}." : "You have been granted a new Admin role.")
: (hasRoleName ? $"You have been assigned to the Self Service role: {roleName}." : "You have been assigned a new Self Service role.");
var notification = new EmployeeNotification
{
EmployeeID = employeeID.Value,
Header = roleType == EnumRoleType.Admin ? "New Admin Role Assigned" : "New Self Service Role Assigned",
Description = description,
Link = "",
CreatedDate = DateTime.Now,
CreatedBy = approverID,
ReferenceID = userRoleID,
IsRead = 0,
ReadDate = null,
ReadBy = null
};
new EmployeeNotificationService().Insert(tc, notification);
}
// The login e-mail the old Save sent to newly created employee logins (now sent on approval).
private void MailNewLogin(List<Employee> oemps)
{
try
{
EmailSettings st = new EmailSettings();
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
IConfiguration Configuration = builder.Build();
Configuration.GetSection("EmailSettings").Bind(st);
foreach (Employee emp in oemps)
{
if (!string.IsNullOrWhiteSpace(emp.EmailAddress))
{
string password = MakePassWord(emp.BirthDate);
MailSender mailSender = new MailSender();
mailSender.AddTo(emp.EmailAddress);
mailSender.Subject = "Your HR software Login information";
mailSender.Body = @"Your HR software Login information are following.
<p> <b>Log-in ID : </b> " + emp.EmployeeNo + "</p>";
mailSender.Body += "<p> <b>Password : </b> " + password.Trim() + "</p>";
mailSender.ThreadSendMail(st);
}
}
}
catch (Exception e)
{
// The roles are already approved; a mail failure must not undo that.
ExceptionLog.Write(e);
}
}
#endregion
internal int Save(TransactionContext tc, UserRole oUserRole, int userRoleID)
{
try
{
if (oUserRole.IsNew)
{
oUserRole.ID = userRoleID;
UserRoleDA.Insert(tc, oUserRole);
}
else
{
UserRoleDA.Update(tc, oUserRole);
}
#region Notification
if (oUserRole.RoleType != null && oUserRole.IsOld != null && oUserRole.IsOld == false &&
(oUserRole.RoleType == EnumRoleType.Self_Service || oUserRole.RoleType == EnumRoleType.Admin))
{
if (oUserRole.employeeID.HasValue)
{
bool hasRoleName = !string.IsNullOrWhiteSpace(oUserRole.NewRoleName);
string description = oUserRole.RoleType == EnumRoleType.Admin
? (hasRoleName
? $"You have been granted Admin access with the role: {oUserRole.NewRoleName}."
: "You have been granted a new Admin role.")
: (hasRoleName
? $"You have been assigned to the Self Service role: {oUserRole.NewRoleName}."
: "You have been assigned a new Self Service role.");
var notification = new EmployeeNotification
{
EmployeeID = oUserRole.employeeID.Value,
Header = oUserRole.RoleType == EnumRoleType.Admin
? "New Admin Role Assigned"
: "New Self Service Role Assigned",
Description = description,
Link = "",
CreatedDate = DateTime.Now,
CreatedBy = oUserRole.CreatedBy,
ReferenceID = oUserRole.ID,
IsRead = 0,
ReadDate = null,
ReadBy = null
};
new EmployeeNotificationService().Insert(tc, notification);
}
}
#endregion
return oUserRole.ID;
}
catch (Exception e)
{
#region Handle Exception
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
//internal int Save2(TransactionContext tc, UserRole oUserRole)
//{
// try
// {
// //if (oUserRole.IsNew)
// //{
// int id = tc.GenerateID("UserRole", "UserRoleID");
// base.SetObjectID(oUserRole, id);
// UserRoleDA.Insert(tc, oUserRole);
// //}
// //else
// //{
// // UserRoleDA.Update(tc, oUserRole);
// //}
// return oUserRole.ID;
// }
// catch (Exception e)
// {
// #region Handle Exception
// ExceptionLog.Write(e);
// throw new ServiceException(e.Message, e);
// #endregion
// }
//}
//internal int Save3(TransactionContext tc, UserRole oUserRole)
//{
// try
// {
// //if (oUserRole.IsNew)
// //{
// //int id = tc.GenerateID("UserRole", "UserRoleID");
// //base.SetObjectID(oUserRole, ID.FromInteger(id));
// //UserRoleDA.Insert(tc, oUserRole);
// //}
// //else
// //{
// UserRoleDA.Update(tc, oUserRole);
// //}
// return oUserRole.ID;
// }
// catch (Exception e)
// {
// #region Handle Exception
// ExceptionLog.Write(e);
// throw new ServiceException(e.Message, e);
// #endregion
// }
//}
public void Delete(int id)
{
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin(true);
UserRoleDA.Delete(tc, id);
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
public void Delete(TransactionContext tc, int id)
{
try
{
UserRoleDA.Delete(tc, id);
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
public void DeleteByUserID(int id)
{
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin(true);
UserRoleDA.DeleteByUserID(tc, id);
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
public DataSet GetRoleAudit(int type, DateTime fromDate, DateTime ToDate)
{
DataSet role = null;
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
role = UserRoleDA.GetRoleAudit(tc, type, fromDate, ToDate);
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return role;
}
public DataTable GetUserMenuByRole(string roleId)
{
DataTable dtMenu = new DataTable();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
DataSet ds = UserRoleDA.GetUserMenuByRole(tc, roleId);
if (ds != null && ds.Tables != null && ds.Tables.Count > 0)
dtMenu = ds.Tables[0];
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return dtMenu;
}
public void DeleteByUserID(TransactionContext tc, int id)
{
try
{
UserRoleDA.DeleteByUserID(tc, id);
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
public void Update(int id, EnumStatus status)
{
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin(true);
UserRoleDA.Update(tc, id, status);
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
}
}