NonInventPurchasingSystem/CPRNIMS.Domain/UIServices/PO/CustomPOService.cs

77 lines
2.6 KiB
C#

using CPRNIMS.Domain.UIContracts.PO;
using CPRNIMS.Infrastructure.Entities.PO;
using CPRNIMS.Infrastructure.Helper;
using Google.Apis.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace CPRNIMS.Domain.UIServices.PO
{
public class CustomPOService : ICustomPOService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly TokenHelper _tokenHelper;
private readonly IConfiguration _configuration;
private readonly ILogger<CustomPOService> _logger;
public CustomPOService(
IHttpClientFactory httpClientFactory,
TokenHelper tokenHelper,
IConfiguration configuration,
ILogger<CustomPOService> logger)
{
_httpClientFactory = httpClientFactory;
_tokenHelper = tokenHelper;
_configuration = configuration;
_logger = logger;
}
public async Task<POFormData> GetPOFormDataAsync(long? poId = null)
{
try
{
var token = await _tokenHelper.GetValidTokenAsync();
if (string.IsNullOrEmpty(token))
throw new UnauthorizedAccessException("No valid token available.");
var httpClient = _httpClientFactory.CreateClient("AuthApi");
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
var url = _configuration["LLI:NonInvent:POMgmt:GetPOFormData"];
if (poId.HasValue)
url += $"?poId={poId}";
var response = await httpClient.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
_logger.LogError("GetPOFormData failed: {StatusCode}", response.StatusCode);
return new POFormData();
}
var json = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize<POFormData>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return result ?? new POFormData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in GetPOFormDataAsync");
return new POFormData();
}
}
}
}