using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Xml.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NTP.Application.Grains.Permits;
namespace NTP.Infrastructure.Grains;
// All classes end in "Service" so the shared convention registration (class X -> interface IX) picks them up without editing the DI files.
/// Binds configuration section "Grains:Permits" (see GrainsPermitsOptions); settings are read once per scope.
internal sealed class GrainsPermitsSettingsService : IGrainsPermitsSettingsService
{
public GrainsPermitsSettingsService(IConfiguration configuration)
{
Value = new GrainsPermitsOptions();
configuration.GetSection(GrainsPermitsOptions.SectionName).Bind(Value);
}
public GrainsPermitsOptions Value { get; }
}
///
/// TCS petroleum permit web service (legacy application.PetWS / ColdFusion cfinvoke). The Axis operation name and namespace are not in the
/// repository: SOAP 1.1 with operation createPermit(xml, flag) / getFopDetail(FOP) is assumed (UNVERIFIED, cannot be called from
/// here). Disabled unless Grains:Permits:Tcs:Enabled is true.
///
internal sealed class TcsPermitGatewayService(IGrainsPermitsSettingsService settings, ILogger logger)
: ITcsPermitGatewayService
{
private static readonly HttpClient Http = new();
private TcsOptions Options => settings.Value.Tcs;
public async Task CreatePermitAsync(TcsPermitRequest r, CancellationToken ct = default)
{
if (!Options.Enabled) return new(null, null, "خدمة TCS غير مفعلة في الإعدادات");
var xml = BuildShipmentXml(r);
try
{
var response = await CallAsync("createPermit", $"{Escape(xml)}1", ct);
var doc = XDocument.Parse(WebUnescape(response));
var kids = doc.Root?.Elements().ToList() ?? [];
if (kids.Count < 3) return new(null, null, "خطأ في الاتصال
استجابة غير متوقعة");
return new(kids[0].Value.Trim(), kids[2].Value.Trim(), string.Empty); // PN, status; kids[1] = error codes (CheckWSError)
}
catch (Exception ex) when (!ct.IsCancellationRequested) // includes our own timeout (TaskCanceledException)
{
logger.LogError(ex, "TCS createPermit failed");
return new(null, null, "خطأ في الاتصال
" + ex.Message);
}
}
public async Task GetFopDetailAsync(string fop, CancellationToken ct = default)
{
if (!Options.Enabled) return Empty("خدمة TCS غير مفعلة في الإعدادات");
try
{
var response = await CallAsync("getFopDetail", $"{Escape(fop)}", ct);
var root = XDocument.Parse(WebUnescape(response)).Root;
if (root is null || !root.HasElements) return Empty(string.Empty);
var k = root.Elements().ToList();
var d = root.Element("DRIVER")?.Elements().ToList() ?? [];
string V(IReadOnlyList l, int i) => i < l.Count ? l[i].Value.Trim() : string.Empty;
return new(string.Empty, V(k, 0), V(k, 1), V(k, 2), V(k, 3), V(k, 6), V(d, 0), V(d, 1), V(d, 2), V(d, 4), V(d, 5), V(d, 6));
}
catch (Exception ex) when (!ct.IsCancellationRequested) // includes our own timeout (TaskCanceledException)
{
logger.LogError(ex, "TCS getFopDetail failed");
return Empty("خطأ في الاتصال
" + ex.Message);
}
}
private static TcsFopDetail Empty(string error) => new(error, "", "", "", "", "", "", "", "", "", "", "");
private async Task CallAsync(string operation, string body, CancellationToken ct)
{
var envelope = $"""
<{operation}>{body}{operation}>
""";
using var req = new HttpRequestMessage(HttpMethod.Post, Options.PermitServiceUrl)
{
Content = new StringContent(envelope, Encoding.UTF8, "text/xml")
};
req.Headers.Add("SOAPAction", "\"\"");
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(5, Options.TimeoutSeconds)));
using var res = await Http.SendAsync(req, cts.Token);
res.EnsureSuccessStatusCode();
var text = await res.Content.ReadAsStringAsync(cts.Token);
var soap = XDocument.Parse(text);
var ret = soap.Descendants().FirstOrDefault(e => e.Name.LocalName.EndsWith("Return", StringComparison.OrdinalIgnoreCase));
return ret?.Value ?? text;
}
private static string WebUnescape(string s) => s;
private static string Escape(string s) => System.Security.SecurityElement.Escape(s) ?? string.Empty;
internal static string BuildShipmentXml(TcsPermitRequest r)
{
var asrn = r.Asrn.Length == 12 && r.Asrn.StartsWith("20", StringComparison.Ordinal) ? r.Asrn : string.Empty;
var crn = asrn.Length == 0 ? r.Asrn : string.Empty;
string A(string? v) => System.Security.SecurityElement.Escape(v ?? string.Empty) ?? string.Empty;
return TcsXmlTemplate.Shipment
.Replace("@@USERID@@", A(r.UserId.ToUpperInvariant())).Replace("@@COMPANYNAME@@", A(r.CompanyName))
.Replace("@@DRVR@@", A(r.Drvr.Trim())).Replace("@@ASRN@@", A(asrn)).Replace("@@CRN@@", A(crn)).Replace("@@FOP@@", A(r.Fop))
.Replace("@@SEALN@@", A(r.SealN)).Replace("@@TST@@", A(r.Tst)).Replace("@@CANNAME@@", A(r.CanName)).Replace("@@CAN@@", A(r.Can))
.Replace("@@TN@@", A(r.Tn)).Replace("@@TRNAT@@", A(r.TrnAt)).Replace("@@TRN@@", A(r.Trn)).Replace("@@TT@@", A(r.Tt))
.Replace("@@NNPN@@", A(r.Nnpn)).Replace("@@NAT@@", A(r.Nat)).Replace("@@CAT@@", A(r.Cat)).Replace("@@DLN@@", A(r.Dln))
.Replace("@@FIRMS@@", A(r.Firms)).Replace("@@INBONDTYPECODE@@", A(r.InbondTypeCode))
.Replace("@@ROUTINGTEMPLATEID@@", r.RoutingTemplateId.ToString()).Replace("@@SHIPMENTMODE@@", A(r.ShipmentMode))
.Replace("@@ORIGINADDRESSID@@", r.OriginAddressId.ToString()).Replace("@@DESTINATIONADDRESSID@@", r.DestinationAddressId.ToString());
}
}
/// Mobile push notifications (legacy NTP.components.MobileNotifications). POSTs {template, payload} JSON to the configured URL.
internal sealed class MobileNotificationGatewayService(IGrainsPermitsSettingsService settings, ILogger logger)
: IMobileNotificationGatewayService
{
private static readonly HttpClient Http = new();
public async Task SendAsync(string template, IReadOnlyDictionary payload, CancellationToken ct = default)
{
var o = settings.Value.Notifications;
if (!o.Enabled || string.IsNullOrWhiteSpace(o.Url)) return;
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds)));
var json = JsonSerializer.Serialize(new { template, payload });
using var res = await Http.PostAsync(o.Url, new StringContent(json, Encoding.UTF8, "application/json"), cts.Token);
if (!res.IsSuccessStatusCode) logger.LogWarning("Notification {Template} -> {Status}", template, (int)res.StatusCode);
}
catch (Exception ex) when (!ct.IsCancellationRequested) // includes our own timeout (TaskCanceledException)
{
// legacy notifications were fire-and-forget; a failure never rolls back the business operation
logger.LogWarning(ex, "Notification {Template} failed", template);
}
}
}
/// Auto dialer / IVR (GrainsFactoryWeb.autoCallService2 and callAPI).
internal sealed class AutoCallGatewayService(IGrainsPermitsSettingsService settings, ILogger logger)
: IAutoCallGatewayService
{
private static readonly HttpClient Http = new();
public async Task SendCallFileAsync(byte[] csv, CancellationToken ct = default)
{
var o = settings.Value.AutoCall;
if (!o.Enabled || string.IsNullOrWhiteSpace(o.SendUrl)) return false;
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds)));
var body = "{\"TYPE\":\"TEST\",\"FILE\":\"" + Convert.ToBase64String(csv) + "\"}";
using var res = await Http.PostAsync(o.SendUrl, new StringContent(body, Encoding.UTF8, new MediaTypeHeaderValue("application/json")), cts.Token);
return res.StatusCode == System.Net.HttpStatusCode.OK;
}
catch (Exception ex) when (!ct.IsCancellationRequested) // includes our own timeout (TaskCanceledException)
{
logger.LogWarning(ex, "Auto call dialer unreachable");
return false;
}
}
// The IVR call is a SOAP web service call that dials every requested truck before it answers, so it runs on its own client
// without the usual timeout, only one call may run at a time, and the screen is told "started" if the answer takes long.
private static readonly HttpClient IvrHttp = new() { Timeout = Timeout.InfiniteTimeSpan };
private static string? _ivrNamespace; // targetNamespace of the IVR service, read once from its WSDL
private static int _ivrRunning; // 1 while a callAPI request is still being served
public async Task TriggerIvrAsync(CancellationToken ct = default)
{
var o = settings.Value.AutoCall;
if (!o.Enabled || string.IsNullOrWhiteSpace(o.IvrUrl)) return IvrTriggerResult.Failed;
if (Interlocked.CompareExchange(ref _ivrRunning, 1, 0) != 0) return IvrTriggerResult.Busy;
var handedOver = false;
try
{
HttpRequestMessage req;
if (o.IvrUrl.EndsWith("?wsdl", StringComparison.OrdinalIgnoreCase))
{
// legacy: createObject("webservice", "...callivr.cfc?wsdl").callAPI() -> SOAP 1.1 request to the CFC itself
var endpoint = o.IvrUrl[..^"?wsdl".Length];
var ns = await IvrNamespaceAsync(o, ct);
var envelope = ""
+ $"";
req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new StringContent(envelope, Encoding.UTF8, "text/xml") };
req.Headers.TryAddWithoutValidation("SOAPAction", "\"\"");
}
else
{
req = new HttpRequestMessage(HttpMethod.Get, o.IvrUrl);
}
var cancelAfter = new CancellationTokenSource(TimeSpan.FromMinutes(Math.Max(1, o.IvrTimeoutMinutes)));
var send = IvrHttp.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cancelAfter.Token);
var first = await Task.WhenAny(send, Task.Delay(TimeSpan.FromSeconds(Math.Max(3, o.IvrWaitSeconds)), CancellationToken.None));
if (first == send)
{
try
{
using var res = await send;
if (!res.IsSuccessStatusCode) logger.LogWarning("IVR answered {Status}", (int)res.StatusCode);
return res.IsSuccessStatusCode ? IvrTriggerResult.Done : IvrTriggerResult.Failed;
}
finally { req.Dispose(); cancelAfter.Dispose(); }
}
// still dialing: the call finishes in the background and releases the single-flight flag when it is over
handedOver = true;
_ = send.ContinueWith(t =>
{
try
{
if (t.IsCompletedSuccessfully) { logger.LogInformation("IVR call finished with {Status}", (int)t.Result.StatusCode); t.Result.Dispose(); }
else logger.LogWarning(t.Exception?.GetBaseException(), "IVR call did not finish");
}
finally { req.Dispose(); cancelAfter.Dispose(); Interlocked.Exchange(ref _ivrRunning, 0); }
}, TaskScheduler.Default);
return IvrTriggerResult.Started;
}
catch (Exception ex) when (!ct.IsCancellationRequested) // includes timeouts (TaskCanceledException)
{
logger.LogWarning(ex, "IVR unreachable");
return IvrTriggerResult.Failed;
}
finally
{
if (!handedOver) Interlocked.Exchange(ref _ivrRunning, 0);
}
}
/// The service namespace is whatever its WSDL says (ColdFusion derives it from the folder); fetched once.
private async Task IvrNamespaceAsync(AutoCallOptions o, CancellationToken ct)
{
if (_ivrNamespace is { } known) return known;
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds)));
var wsdl = await Http.GetStringAsync(o.IvrUrl, cts.Token);
var m = System.Text.RegularExpressions.Regex.Match(wsdl, "targetNamespace\\s*=\\s*\"([^\"]+)\"");
if (!m.Success) throw new InvalidOperationException("The IVR WSDL has no targetNamespace");
return _ivrNamespace = m.Groups[1].Value;
}
}
///
/// External weighbridge database (legacy datasource GrainsWeighbridge, table CARGO). The database engine of that datasource is not known
/// (the connection is defined in the ColdFusion administrator, not in the repository), so no driver is bundled: this source reports
/// "not configured" and the weighbridge sync jobs skip. Provide another IWeighbridgeSourceService implementation to enable them.
///
internal sealed class WeighbridgeSourceService : IWeighbridgeSourceService
{
public bool IsConfigured => false;
public Task> ReadNewAsync(long locationId, DateTime? after, CancellationToken ct = default) =>
Task.FromResult>([]);
}