tycg_carviolation_BE/Traffic.Service/Implements/AccountService.cs

574 lines
21 KiB
C#

using LiangLiSystem.Services.Helpers;
using Microsoft.Extensions.Logging;
using Omu.ValueInjecter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Traffic.Data.Enums;
using Traffic.Data.Models;
using Traffic.Data.ViewModels;
using Traffic.Repository.Infrastructures;
using Traffic.Service.Interfaces;
namespace Traffic.Service.Implements
{
public class AccountService : IAccountService
{
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger _logger;
public AccountService(IUnitOfWork unitOfWork, ILogger<AccountService> logger)
{
_unitOfWork = unitOfWork;
_logger = logger;
}
public AccountUserViewModel GetAccountUser(int id)
{
try
{
//user
var user = _unitOfWork.AccountRepository.GetAccountUserById(id);
_logger.LogError($"GetAccountUser user id = {id}");
if (user == null)
{
_logger.LogError($"GetAccountUser user id = {id} is null");
return null;
}
//station
var station = _unitOfWork.PoliceStationRepository.GetPoliceStationById(user.PoliceStationId);
if (station == null)
{
_logger.LogError($"GetAccountUser station = {user.PoliceStationId} is null");
return null;
}
var policeStationViewModel = new PoliceStationViewModel
{
Id = station.Id,
StationName = station.StationName,
Area = station.Area
};
//site
var sites = _unitOfWork.AccountRepository.GetAccountUserSite(id);
if (sites == null)
{
_logger.LogError($"GetAccountUser sites is null");
return null;
}
var sitesViewModel = new List<UserSiteViewModel>();
var siteInfo = _unitOfWork.SiteInformationRepository.GetSiteInformations();
foreach (var item in sites)
{
var siteVM = new UserSiteViewModel
{
Id = item.Id,
SiteId = siteInfo.FirstOrDefault(i => i.Id == item.SiteId).SiteID,
SiteName = siteInfo.FirstOrDefault(i => i.Id == item.SiteId).SiteName
};
sitesViewModel.Add(siteVM);
}
return new AccountUserViewModel
{
Id = id,
Account = user.Account,
Name = user.UserName,
Email = user.Email,
Phone = user.PhoneNumber,
Role = user.RoleCodeId,
PoliceStation = policeStationViewModel,
Site = sitesViewModel,
Status = user.Status
};
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return new AccountUserViewModel();
}
}
public bool GetExistUser(string account)
{
try
{
var user = _unitOfWork.AccountRepository.GetAccountUserByAccount(account);
return user != null;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return false;
}
}
public TradeResultModel InserAccountUser(int byWho, UserData account)
{
var result = new TradeResultModel { Success = false };
try
{
SHA256 sha256 = new SHA256CryptoServiceProvider();//建立一個SHA256
byte[] source = Encoding.Default.GetBytes("000000");//將字串轉為Byte[]
byte[] crypto = sha256.ComputeHash(source);//進行SHA256加密
var accountUser = new AccountUser
{
Password = Convert.ToBase64String(crypto),//把加密後的字串從Byte[]轉為字串
Account = account.Account,
UserName = account.UserName,
Email = account.Email,
PhoneNumber = account.PhoneNumber,
CreatorId = byWho,
CreatedOn = Util.GetDateTimeNow(),
RoleCodeId = account.RoleCode_Id,
PoliceStationId = account.GroupCode_Id,
ChangePwdOn = Util.GetDateTimeNow(),
};
var id = _unitOfWork.AccountRepository.InsertAccountUser(accountUser);
var sites = new List<AccountUserSite>();
foreach (var item in account.Site_Id)
{
var site = new AccountUserSite
{
UserId = id,
SiteId = item
};
sites.Add(site);
}
bool isSuccess = _unitOfWork.AccountRepository.InsertAccountUserSite(sites);
_unitOfWork.Complete();
result.Success = isSuccess;
return result;
}
catch (Exception ex)
{
_unitOfWork.Rollback();
result.Message = ex.Message;
_logger.LogError(ex.Message);
return result;
}
}
public PageViewModel<IEnumerable<UserDataQuery>> GetUserDataList(SearchModel searchModel, int? userId)
{
try
{
var sql = _unitOfWork.AccountRepository.GetAccountUsers();
if (!string.IsNullOrEmpty(searchModel.Term))
{
sql = sql.Where(x => x.Account.Contains(searchModel.Term) || x.UserName.Contains(searchModel.Term));
}
if (userId != null)
{
sql = sql.Where(x => userId == x.Id);
}
int count = -1;
int pageCount = -1;
if (searchModel.Page == 1)
{
count = sql.Count();
if (count % 10 != 0)
{
pageCount = (count / searchModel.PageSize) + 1;
}
else
{
pageCount = count / searchModel.PageSize;
}
}
switch (searchModel.Order)
{
case "Id":
sql = searchModel.IsAsc ? sql.OrderBy(x => x.Id) : sql.OrderByDescending(x => x.Id);
break;
case "Account":
sql = searchModel.IsAsc ? sql.OrderBy(x => x.Account).ThenBy(x => x.Id) : sql.OrderByDescending(x => x.Account).ThenByDescending(x => x.Id);
break;
case "UserName":
sql = searchModel.IsAsc ? sql.OrderBy(x => x.UserName).ThenBy(x => x.Id) : sql.OrderByDescending(x => x.Account).ThenByDescending(x => x.Id);
break;
case "GroupCodeId":
sql = searchModel.IsAsc ? sql.OrderBy(x => x.PoliceStationId).ThenBy(x => x.Id) : sql.OrderByDescending(x => x.PoliceStationId).ThenByDescending(x => x.Id);
break;
case "RoleCodeId":
sql = searchModel.IsAsc ? sql.OrderBy(x => x.RoleCodeId).ThenBy(x => x.Id) : sql.OrderByDescending(x => x.RoleCodeId).ThenByDescending(x => x.Id);
break;
default:
goto case "Id";
}
//station
var stations = _unitOfWork.PoliceStationRepository.GetPoliceStations();
var stationsViewModel = new List<PoliceStationViewModel>();
foreach (var item in stations)
{
var policeStationViewModel = new PoliceStationViewModel
{
Id = item.Id,
Area = item.Area,
StationName = item.StationName,
};
stationsViewModel.Add(policeStationViewModel);
}
//site
var sites = _unitOfWork.AccountRepository.GetAccountUserSites();
if (sites == null)
{
_logger.LogError($"GetAccountUser sites is null");
return null;
}
var sitesViewModel = new List<UserSiteViewModel>();
var siteInfo = _unitOfWork.SiteInformationRepository.GetSiteInformations();
foreach (var item in sites)
{
var siteVM = new UserSiteViewModel
{
Id = item.SiteId,
SiteId = siteInfo.FirstOrDefault(i => i.Id == item.SiteId).SiteID,
SiteName = siteInfo.FirstOrDefault(i => i.Id == item.SiteId).SiteName
};
sitesViewModel.Add(siteVM);
}
sql = sql.Skip((searchModel.Page - 1) * searchModel.PageSize).Take(searchModel.PageSize);
var data = sql.ToList().Select(x => new UserDataQuery
{
Id = x.Id,
Account = x.Account,
UserName = x.UserName,
Email = x.Email,
PhoneNumber = x.PhoneNumber,
GroupCode_Id = x.PoliceStationId,
RoleCode_Id = x.RoleCodeId,
CreatorId = x.CreatorId.ToString(),
CreatedOn = x.CreatedOn.ToString(),
PoliceStation = stationsViewModel.FirstOrDefault(i => i.Id == x.PoliceStationId),
Status = x.Status,
Site = sites.Where(i => i.UserId == x.Id).Select(y => new UserSiteViewModel
{
Id = y.SiteId,
SiteId = siteInfo.FirstOrDefault(i => i.Id == y.SiteId).SiteID,
SiteName = siteInfo.FirstOrDefault(i => i.Id == y.SiteId).SiteName
}).ToList()
});
return new PageViewModel<IEnumerable<UserDataQuery>>
{
RowCount = count,
PageCount = pageCount,
CurrentPage = searchModel.Page,
Data = data,
};
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return null;
}
}
public TradeResultModel UpdateAccountbyAdmin(int byWho, UserData account)
{
var result = new TradeResultModel { Success = false };
try
{
var accountUser = new AccountUser
{
Id = account.Id,
Account = account.Account,
UserName = account.UserName,
Email = account.Email,
PhoneNumber = account.PhoneNumber,
PoliceStationId = account.GroupCode_Id,
RoleCodeId = account.RoleCode_Id,
UpdatorId = byWho,
UpdatedOn = Util.GetDateTimeNow(),
};
var sites = new List<AccountUserSite>();
foreach (var item in account.Site_Id)
{
var site = new AccountUserSite
{
UserId = account.Id,
SiteId = item
};
sites.Add(site);
}
_unitOfWork.AccountRepository.DeleteUserSite(account.Id);
_unitOfWork.AccountRepository.InsertAccountUserSite(sites);
var IsSuccess = _unitOfWork.AccountRepository.UpdateAccountUserbyAdmin(accountUser);
if (IsSuccess)
{
_unitOfWork.Complete();
}
else
{
_unitOfWork.Rollback();
}
result.Success = IsSuccess;
return result;
}
catch (Exception ex)
{
_unitOfWork.Rollback();
result.Message = ex.Message;
_logger.LogError(ex.Message);
return result;
}
}
public TradeResultModel UpdateAccountbyUser(int byWho, UserData account)
{
var result = new TradeResultModel { Success = false };
try
{
var accountUser = new AccountUser
{
Id = byWho,
UserName = account.UserName,
Email = account.Email,
PhoneNumber = account.PhoneNumber,
UpdatorId = byWho,
UpdatedOn = Util.GetDateTimeNow(),
};
var IsSuccess = _unitOfWork.AccountRepository.UpdateAccountUserbyUser(accountUser);
if (IsSuccess)
{
_unitOfWork.Complete();
}
else
{
_unitOfWork.Rollback();
}
result.Success = IsSuccess;
return result;
}
catch (Exception ex)
{
_unitOfWork.Rollback();
result.Message = ex.Message;
_logger.LogError(ex.Message);
return result;
}
}
public TradeResultModel UpdateAccountPasswordbyAdmin(int id, int byWho)
{
var result = new TradeResultModel { Success = false };
SHA256 sha256 = new SHA256CryptoServiceProvider();
byte[] source = Encoding.Default.GetBytes("000000");
byte[] crypto = sha256.ComputeHash(source);
var newPassword = Convert.ToBase64String(crypto);
try
{
var account = _unitOfWork.AccountRepository.GetAccountUserById(id);
if (account != null)
{
_unitOfWork.AccountRepository.UpdateAccountUserPasswordByAdmin(id, newPassword, byWho, Util.GetDateTimeNow());
_unitOfWork.Complete();
result.Success = true;
}
else
{
result.Success = false;
result.Message = "No This User";
}
}
catch (Exception ex)
{
_unitOfWork.Rollback();
result.Message = ex.Message;
_logger.LogError(ex.Message);
return result;
}
return result;
}
public TradeResultModel UpdateAccountPasswordByUser(int ByWho, UserData accountViewModel)
{
var result = new TradeResultModel { Success = false };
var pwdTimes = _unitOfWork.AccountRepository.GetAccountPwdTop3(accountViewModel.Account);
if (!Util.IsValidPassword(accountViewModel.NewPassword))
{
result.Success = false;
result.Message = "Please enter a valid password";
}
else
{
SHA256 sha256 = new SHA256CryptoServiceProvider();
byte[] source = Encoding.Default.GetBytes(accountViewModel.Password);
byte[] crypto = sha256.ComputeHash(source);
var oldPassword = Convert.ToBase64String(crypto);
SHA256 newSha256 = new SHA256CryptoServiceProvider();
byte[] newSource = Encoding.Default.GetBytes(accountViewModel.NewPassword);
byte[] newCrypto = newSha256.ComputeHash(newSource);
var newPassword = Convert.ToBase64String(newCrypto);
try
{
var account = _unitOfWork.AccountRepository.GetAccountUserById(accountViewModel.Id);
if (account == null || account.Password != oldPassword)
{
result.Success = false;
result.Message = "wrong password";
}
else if (pwdTimes.Any(i => i.Password == newPassword))
{
result.Success = false;
result.Message = "修改密碼不可以與前三次相同";
}
else
{
var createOn = Util.GetDateTimeNow();
_unitOfWork.AccountRepository.UpdateAccountUserPasswordByUser(ByWho, oldPassword, newPassword, createOn);
_unitOfWork.AccountRepository.InsertAccountPwd(new AccountPwd() { Account = account.Account, Password = newPassword, CreatedOn = createOn });
_unitOfWork.Complete();
result.Success = true;
}
}
catch (Exception ex)
{
_unitOfWork.Rollback();
result.Message = ex.Message;
_logger.LogError(ex.Message);
return result;
}
}
return result;
}
public IEnumerable<UserNameList> GetUserNameList()
{
try
{
var data = _unitOfWork.AccountRepository.GetAccountUsers().Select(x => new UserNameList
{
Id = x.Id,
UserName = x.UserName,
Email = x.Email
});
return data;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return new List<UserNameList>();
}
}
public TradeResultModel DeleteUserData(int id)
{
var result = new TradeResultModel { Success = false };
try
{
var data = _unitOfWork.AccountRepository.GetAccountUserById(id);
if (data != null)
{
_unitOfWork.AccountRepository.DeleteUser(id);
_unitOfWork.Complete();
}
}
catch (Exception ex)
{
_unitOfWork.Rollback();
result.Message = ex.Message;
_logger.LogError(ex.Message);
return result;
}
result.Success = true;
return result;
}
public TradeResultModel PutUserbyAdmin(int byWho, int id, int status)
{
var result = new TradeResultModel { Success = false };
try
{
var isSuccess = _unitOfWork.AccountRepository.DisableUser(byWho, id, status);
if (!isSuccess)
{
result.Success = false;
result.Message = "修改失敗";
return result;
}
_unitOfWork.Complete();
result.Success = true;
return result;
}
catch (Exception ex)
{
_unitOfWork.Rollback();
result.Message = ex.Message;
_logger.LogError(ex.Message);
return result;
}
}
public IEnumerable<string> GetUserSite(int id)
{
try
{
var siteInfo = _unitOfWork.SiteInformationRepository.GetSiteInformations();
var datas = _unitOfWork.AccountRepository.GetAccountUserSite(id);
var result = new List<string>();
foreach (var site in datas)
{
result.Add(siteInfo.FirstOrDefault(s => s.Id == site.SiteId).SiteName);
}
return result;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return new List<string>();
}
}
public IEnumerable<UserSiteInformationViewModel> GetUserSiteInfo(int id)
{
try
{
var siteInfo = _unitOfWork.SiteInformationRepository.GetSiteInformations();
var datas = _unitOfWork.AccountRepository.GetAccountUserSite(id);
var result = new List<UserSiteInformationViewModel>();
foreach (var site in datas)
{
var s = siteInfo.FirstOrDefault(s => s.Id == site.SiteId);
var siteViewModel = new UserSiteInformationViewModel();
siteViewModel.InjectFrom(s);
siteViewModel.Id = site.Id;
result.Add(siteViewModel);
}
return result;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return new List<UserSiteInformationViewModel>();
}
}
}
}