hrms-api-exam/Services/DistrictService.cs

101 lines
3.5 KiB
C#
Raw Normal View History

2023-03-23 12:31:21 +07:00
using System.Security.Claims;
using BMA.EHR.Recurit.Exam.Service.Data;
using BMA.EHR.Recurit.Exam.Service.Models;
using Microsoft.EntityFrameworkCore;
namespace BMA.EHR.Recurit.Exam.Service.Services
{
public class DistrictService
{
#region " Fields "
private readonly ApplicationDbContext _context;
private readonly IHttpContextAccessor _httpContextAccessor;
#endregion
#region " Constructor and Destructor "
public DistrictService(ApplicationDbContext context,
IHttpContextAccessor httpContextAccessor)
{
_context = context;
_httpContextAccessor = httpContextAccessor;
}
#endregion
#region " Properties "
private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value;
#endregion
#region " Methods "
public async Task<IEnumerable<District>> GetsAsync(string provinceId, bool showAll = true)
{
if (showAll)
return await _context.Districts.AsQueryable()
.Where(x => x.Province.Id == Guid.Parse(provinceId))
.OrderBy(d => d.Name)
.ToListAsync();
else
return await _context.Districts.AsQueryable()
.Where(x => x.Province.Id == Guid.Parse(provinceId))
.Where(p => p.IsActive)
.OrderBy(d => d.Name)
.ToListAsync();
}
public async Task<District?> GetByIdAsync(Guid id)
{
return await _context.Districts.FirstOrDefaultAsync(x => x.Id == id);
}
public async Task UpdateAsync(Guid id, District updated)
{
var existData = await _context.Districts.FirstOrDefaultAsync(x => x.Id == id);
if (existData != null)
{
if (existData.Name != updated.Name)
{
existData.Name = updated.Name;
existData.LastUpdatedAt = DateTime.Now;
existData.LastUpdateUserId = UserId ?? "";
existData.LastUpdateFullName = FullName ?? "";
}
if (existData.IsActive != updated.IsActive)
{
existData.IsActive = updated.IsActive;
existData.LastUpdatedAt = DateTime.Now;
existData.LastUpdateUserId = UserId ?? "";
existData.LastUpdateFullName = FullName ?? "";
}
await _context.SaveChangesAsync();
}
}
public async Task CreateAsync(District inserted, string provinceId)
{
var province = await _context.Provinces.FirstOrDefaultAsync(x => x.Id == Guid.Parse(provinceId));
inserted.CreatedUserId = UserId ?? "";
inserted.CreatedFullName = FullName ?? "System Administrator";
inserted.CreatedAt = DateTime.Now;
inserted.LastUpdatedAt = DateTime.Now;
inserted.LastUpdateFullName = FullName ?? "System Administrator";
inserted.LastUpdateUserId = UserId ?? "";
inserted.Province = province;
await _context.Districts.AddAsync(inserted);
await _context.SaveChangesAsync();
}
#endregion
}
}