NTP_V2/src/NTP.Infrastructure/Integrations/JopetrolGateway.cs

83 lines
4.5 KiB
C#

using System.Security;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NTP.Application.Refinery.Integrations;
namespace NTP.Infrastructure.Integrations;
/// <summary>
/// Section <c>Refinery:Jopetrol</c>. OFF by default. <see cref="UserName"/> and <see cref="Password"/> are secrets: they come only from the
/// environment / server .env (<c>Refinery__Jopetrol__UserName</c>, <c>Refinery__Jopetrol__Password</c>), never from a file in the repository.
/// </summary>
public sealed class JopetrolOptions
{
public const string SectionName = "Refinery:Jopetrol";
public const string HttpClientName = "Jopetrol";
public bool Enabled { get; set; }
/// <summary>The ASMX endpoint of the Jopetrol TransportPaymentWS service.</summary>
public string Url { get; set; } = "";
public string UserName { get; set; } = "";
public string Password { get; set; } = "";
public int TimeoutSeconds { get; set; } = 30;
}
/// <summary>Request building and answer parsing of the Jopetrol SOAP call (kept apart from the HTTP code so it can be tested).</summary>
public static class JopetrolSoap
{
public const string SoapNamespace = "http://www.w3.org/2003/05/soap-envelope";
public const string ServiceNamespace = "http://jopetrol.com.jo/TransportPaymentWS";
/// <summary>The envelope of legacy callRefinaryUpdateStatusTo7 (SOAP 1.2, AuthHeader + sendClaimandUpdateStatusTo7 with TransNumber and claimNo).</summary>
public static string BuildEnvelope(string userName, string password, string pn, string claimNo)
{
static string E(string s) => SecurityElement.Escape(s) ?? "";
return $"""
<soap:Envelope xmlns:soap="{SoapNamespace}" xmlns:tran="{ServiceNamespace}">
<soap:Header><tran:AuthHeader><tran:UserName>{E(userName)}</tran:UserName><tran:Password>{E(password)}</tran:Password></tran:AuthHeader></soap:Header>
<soap:Body><tran:sendClaimandUpdateStatusTo7><tran:TransNumber>{E(pn)}</tran:TransNumber><tran:claimNo>{E(claimNo)}</tran:claimNo></tran:sendClaimandUpdateStatusTo7></soap:Body>
</soap:Envelope>
""";
}
/// <summary>Text of <c>sendClaimandUpdateStatusTo7Result</c> (legacy xmlSearch "//*[local-name()=...]"); null when the answer does not contain it.</summary>
public static string? ParseResult(string xml)
{
var doc = XDocument.Parse(xml);
return doc.Descendants().FirstOrDefault(e => e.Name.LocalName == "sendClaimandUpdateStatusTo7Result")?.Value;
}
}
/// <summary>
/// Jopetrol claim web service (legacy refinery_wage_claimfactory.callRefinaryUpdateStatusTo7). Returns null WITHOUT any call when
/// <c>Refinery:Jopetrol:Enabled</c> is false. HTTP errors, time-outs and unreadable answers are thrown (the caller decides what to tell the user).
/// </summary>
public sealed class JopetrolGateway(IHttpClientFactory httpClients, IOptions<JopetrolOptions> options, ILogger<JopetrolGateway> logger) : IJopetrolGateway
{
public async Task<string?> SendClaimAndUpdateStatusTo7Async(string pn, string claimNo, CancellationToken ct = default)
{
var o = options.Value;
if (!o.Enabled) return null;
if (string.IsNullOrWhiteSpace(o.Url) || string.IsNullOrWhiteSpace(o.UserName) || string.IsNullOrWhiteSpace(o.Password))
throw new InvalidOperationException("Refinery:Jopetrol is enabled but Url / UserName / Password are not configured.");
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(o.TimeoutSeconds is > 0 and <= 300 ? o.TimeoutSeconds : 30));
using var request = new HttpRequestMessage(HttpMethod.Post, o.Url)
{
Content = new StringContent(JopetrolSoap.BuildEnvelope(o.UserName, o.Password, pn, claimNo), Encoding.UTF8, "text/xml"),
};
using var response = await httpClients.CreateClient(JopetrolOptions.HttpClientName).SendAsync(request, cts.Token);
var body = await response.Content.ReadAsStringAsync(cts.Token);
logger.LogInformation("Jopetrol sendClaimandUpdateStatusTo7 for permit {Pn}: HTTP {Status}", pn, (int)response.StatusCode);
// legacy parsed whatever came back; a SOAP fault or an HTML error page has no result element
try { return JopetrolSoap.ParseResult(body) ?? ""; }
catch (XmlException) { throw new InvalidOperationException($"Jopetrol answered HTTP {(int)response.StatusCode} with an unreadable body."); }
}
}