hrms-api-backend/BMA.EHR.Application/Repositories/GenericRepository.cs
Suphonchai Phoonsawat f081034e36
Some checks failed
release-dev / release-dev (push) Failing after 11s
fix hangfire แยก job ออกจากกัน และแก้เรื่องการส่ง token
2025-11-11 10:40:49 +07:00

247 lines
8.3 KiB
C#

using Amazon.Runtime.Internal.Endpoints.StandardLibrary;
using Amazon.S3.Model.Internal.MarshallTransformations;
using BMA.EHR.Application.Common.Interfaces;
using BMA.EHR.Domain.Models.Base;
using BMA.EHR.Domain.Models.HR;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
namespace BMA.EHR.Application.Repositories
{
public class GenericRepository<S, T> : IGenericRepository<S, T> where T : class
{
#region " Field "
private readonly IApplicationDBContext _dbContext;
private readonly DbSet<T> _dbSet;
private readonly IHttpContextAccessor _httpContextAccessor;
#endregion
#region " Constructor and Destructor "
public GenericRepository(IApplicationDBContext dbContext,
IHttpContextAccessor httpContextAccessor)
{
_dbContext = dbContext;
_dbSet = _dbContext.Set<T>();
_httpContextAccessor = httpContextAccessor;
// _configuration = configuration;
}
#endregion
#region " Properties "
protected string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
protected string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value;
protected bool? IsPlacementAdmin => _httpContextAccessor?.HttpContext?.User?.IsInRole("placement1");
protected string? AccessToken => _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"];
#endregion
#region " Methods "
#region " For Call External API "
protected async Task<string> GetExternalAPIAsync(string apiPath, string accessToken, string apiKey)
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api_key", apiKey);
var _res = await client.GetAsync(apiPath);
if (_res.IsSuccessStatusCode)
{
var _result = await _res.Content.ReadAsStringAsync();
return _result;
}
return string.Empty;
}
}
catch
{
throw;
}
}
protected async Task<string> SendExternalAPIAsync(HttpMethod method, string apiPath, string accessToken, object? body, string apiKey)
{
try
{
// สร้าง request message
var request = new HttpRequestMessage(method, apiPath);
var json = JsonConvert.SerializeObject(body);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api_key", apiKey);
var _res = await client.SendAsync(request);
if (_res.IsSuccessStatusCode)
{
var _result = await _res.Content.ReadAsStringAsync();
return _result;
}
return string.Empty;
}
}
catch
{
throw;
}
}
protected async Task<string> PostExternalAPIAsync(string apiPath, string accessToken, object? body, string apiKey)
{
try
{
var json = JsonConvert.SerializeObject(body);
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
//stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api_key", apiKey);
var _res = await client.PostAsync(apiPath, stringContent);
if (_res.IsSuccessStatusCode)
{
var _result = await _res.Content.ReadAsStringAsync();
return _result;
}
return string.Empty;
}
}
catch
{
throw;
}
}
protected async Task<bool> PostExternalAPIBooleanAsync(string apiPath, string accessToken, object? body, string apiKey)
{
try
{
var json = JsonConvert.SerializeObject(body);
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api_key", apiKey);
var _res = await client.PostAsync(apiPath, stringContent);
return _res.IsSuccessStatusCode;
}
}
catch
{
throw;
}
}
#endregion
public async Task<Guid> GetProfileOrganizationAsync(string citizenId)
{
try
{
var pf = await _dbContext.Set<Profile>()
.Where(x => x.CitizenId == citizenId)
.Where(x => x.ProfileType.ToLower().Trim() == "officer" && x.IsActive && !x.IsLeave)
.FirstOrDefaultAsync();
return pf == null || pf.Oc == null ? Guid.Empty : pf.OcId!.Value;
}
catch
{
throw;
}
}
public async Task<bool> CheckIsActiveOfficerAsync(string citizenId)
{
try
{
var pf = await _dbContext.Set<Profile>()
.Where(x => x.CitizenId == citizenId)
.Where(x => x.ProfileType.ToLower().Trim() == "officer" && x.IsActive && !x.IsLeave)
.FirstOrDefaultAsync();
return pf != null;
}
catch
{
throw;
}
}
public virtual async Task<IReadOnlyList<T>> GetAllAsync()
{
return await _dbSet.ToListAsync();
}
public virtual async Task<T?> GetByIdAsync(S id)
{
return await _dbSet.FindAsync(id);
}
public virtual async Task<T> AddAsync(T entity)
{
if (entity is EntityBase)
{
(entity as EntityBase).CreatedUserId = UserId!;
(entity as EntityBase).CreatedFullName = FullName!;
(entity as EntityBase).CreatedAt = DateTime.Now;
}
await _dbSet.AddAsync(entity);
await _dbContext.SaveChangesAsync();
return entity;
}
public virtual async Task<T> UpdateAsync(T entity)
{
if (entity is EntityBase)
{
(entity as EntityBase).LastUpdateUserId = UserId!;
(entity as EntityBase).LastUpdateFullName = FullName!;
(entity as EntityBase).LastUpdatedAt = DateTime.Now;
}
_dbSet.Update(entity);
await _dbContext.SaveChangesAsync();
return entity;
}
public virtual async Task DeleteAsync(T entity)
{
_dbSet.Remove(entity);
await _dbContext.SaveChangesAsync();
}
#endregion
}
}