Port mobile notifications: push via legacy SOAP service, SMS for owners without the app, per-environment settings

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-18 10:24:26 +03:00
parent cc0cde3219
commit e03179917f
15 changed files with 758 additions and 28 deletions

View File

@ -7,4 +7,7 @@ Jwt__Key=
# origin users open in the browser, exactly as typed in the address bar
Cors__AllowedOrigins__0=https://<production-host>
# logins that may hold role SU (none by default in production), e.g. Auth__SuperUsers__0=login
# SMS account for owners without the app (secret; without it the SMS is skipped with a warning)
# Grains__Permits__Notifications__Sms__UserName=
# Grains__Permits__Notifications__Sms__Password=
# NTP_PORT=8081

View File

@ -34,6 +34,7 @@ Set these in the server's environment (IIS application settings, a Windows servi
| `Jwt__Key` | JWT signing key, at least 32 random characters. The app refuses to start outside Development without it |
| `Cors__AllowedOrigins__0` | Origin of the web app, e.g. `https://<web-host>`. Replaces the placeholder in the settings file; until it is set no browser origin is allowed |
| `Auth__SuperUsers__0`, `__1` ... | Logins that may hold role `SU`. Empty in production by default; QA lists its own in `appsettings.QA.json` |
| `Grains__Permits__Notifications__Sms__UserName`, `__Password` | SMS provider account (production only; secret). Notification settings: `Grains:Permits:Notifications` (Enabled, PushUrl, SendSmsToOwnersWithoutApp = legacy SEND_SMS_GN_DIST, Sms:Enabled/Provider). Development: off; QA: push on, SMS off; production: push on, SMS on |
Connection string shape (values are examples only):
`User Id=<schema>;Password=<secret>;Data Source=<host>:1521/<service>;Min Pool Size=1;Max Pool Size=50;Connection Timeout=15;Statement Cache Size=50`

View File

@ -23,7 +23,7 @@ repository: everything a new person needs is in these two files, `docs/ENVIRONME
4. `Grains:Registry:UploadedFilesPath` must be a plain path (`/mnt/NTPFiles`), never a `host:container` mapping.
5. `appsettings.Production.json` sets: attachment paths, `Grains:Permits:AutoCall` (enabled, IVR WSDL address), ownership code lists (`BadiyaOwnershipCodes 3,2`, `OtherOwnershipCodes 1,2` - confirm against production `SYSTEM_VARIABLES`).
6. The provider of the dialer must call `/api/v1/grains/permit-autocall/callback` with header `X-Api-Key`; nothing in the repo repoints it.
7. Mobile push / SMS (legacy Firebase) is **not ported**: `Grains:Permits:Notifications` only posts to a URL that does not exist yet (disabled by default).
7. Mobile notifications are ported (see 3.5): production pushes through the legacy web service `http://aqtcs.nafith.net/backend/common/MobileNotification.cfc` and sends the SMS for owners without the app (`SEND_SMS_GN_DIST` = 1). Put the SMS account in the server `.env`: `Grains__Permits__Notifications__Sms__UserName` and `__Password` (until then the SMS is skipped with a warning). Provider `JORMALL` is a guess (the AqabaTCS app uses it): confirm which provider NTP used (`application.SMS_PROVIDER`).
8. The NTP database user needs INSERT on `SYSTEM_ERRORS` and SELECT on `SEQ_SYSTEM_ERRORS`, otherwise error logging only writes a warning to the API log.
9. After deploy: `docker exec ntpv2-prod date` (Amman time), `/health/ready`, sign in, open a truck attachment, click الاتصال الصوتي once (it really dials every requested truck: do not test casually).
10. Database scripts: see docs/ENVIRONMENTS.md ("Database objects"). They are applied by hand; which ones ran on which environment is not recorded: check the tables before re-running (all are safe to re-run).
@ -56,3 +56,8 @@ Role and groups: `select * from roles where code='GTO'`, `select id,name,stakeho
Who holds a legacy action: `select ga.actionid, listagg(g.name,',') within group (order by g.name) from group_actions ga join groups g on g.id=ga.groupid and g.status=1 where ga.actionid in (73,74,93,94) group by ga.actionid`.
Screen rights per role: `select rolecode, count(*) from grains_screen_permissions group by rolecode`.
Ownership lists: `select name, value from system_variables where upper(name) like '%OWNERSHIP%'`.
### 3.5 Mobile notifications (ported from components/MobileNotifications.cfc)
Flow per template (CONFIRM_PN, PHONE_REJECT, DELAY_PN, DISTRIBUTE_PACKED_BULK_OWNERS / _OWNERS_COMPANIES / _COMP): find the app users (driver DRVR and owner TRKOWNER by the truck phone, dispatchers DISP by company login), read their ACTIVE devices (USERDEVICEINFO), fill the NOTIFICATIONMESSAGETEMPLATE text (VAR1..VARn, first occurrence only, as ColdFusion Replace), call SendFromCF9 of the legacy push web service (it sends the OneSignal push and writes MOBILENOTIFICATIONSLOG). It runs in the background in its own scope (legacy used a thread); a failure only goes to the API log and SYSTEM_ERRORS. Owners distribution: an account with no active device gets an SMS with the app link when SendSmsToOwnersWithoutApp (legacy SEND_SMS_GN_DIST) is on, logged in USER_SMS_LOGS. Same legacy quirk: no account for the phone = no SMS.
The SQL was checked read-only on the QA database (all 7 templates exist). **Not tested end to end**: no real push or SMS was sent, and the SOAP envelope for SendFromCF9 was built from its WSDL, not captured from legacy. Difference: the SMS log status is the real HTTP result (legacy always wrote SUCCESS). Still not ported: the push of addPhoneAcceptEvent (phone approval import) and the tender-order publishMobile switch. The legacy files hold the old Firebase and SMS provider keys in clear text (MobileNotifications.cfc, SMS.cfc): rotate them.

View File

@ -4,6 +4,8 @@
},
// the job scheduler never runs on a developer machine (a shared database would run its jobs twice); "run now" still works
"Jobs": { "SchedulerEnabled": false },
// no pushes or SMS from a developer machine (SEND_SMS_GN_DIST = 0)
"Grains": { "Permits": { "Notifications": { "Enabled": false, "SendSmsToOwnersWithoutApp": false } } },
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@ -38,6 +38,14 @@
"BadiyaOwnershipCodes": [ "3", "2" ],
"OtherOwnershipCodes": [ "1", "2" ],
// push on; SMS to owners without the app on (legacy SEND_SMS_GN_DIST = 1). The SMS account (Sms:UserName / Sms:Password) comes from the
// server .env: Grains__Permits__Notifications__Sms__UserName / __Password. Until they are set the SMS is skipped with a warning.
"Notifications": {
"Enabled": true,
"SendSmsToOwnersWithoutApp": true,
"Sms": { "Enabled": true, "Provider": "JORMALL" }
},
"AutoCall": {
"Enabled": true,
"IvrUrl": "http://aqtcs.nafith.net/IVR/callivr.cfc?wsdl"

View File

@ -21,6 +21,13 @@
"SuperUsers": [ "samer", "QA", "MATHHER" ]
},
// Push notifications on, SMS off (legacy SEND_SMS_GN_DIST = 0 in QA).
"Grains": {
"Permits": {
"Notifications": { "Enabled": true, "SendSmsToOwnersWithoutApp": false }
}
},
"Oracle": {
"MinPoolSize": 2,
"MaxPoolSize": 50

View File

@ -27,6 +27,19 @@
"AllowedOrigins": [ "http://localhost:5173" ]
},
// Mobile notifications (legacy MobileNotifications.cfc). Off here: a switched-on environment pushes to the real devices of USERDEVICEINFO.
// QA and production switch it on in their own files. Sms:UserName / Sms:Password are secrets (env vars Grains__Permits__Notifications__Sms__UserName ...).
"Grains": {
"Permits": {
"Notifications": {
"Enabled": false,
"PushUrl": "http://aqtcs.nafith.net/backend/common/MobileNotification.cfc?wsdl",
"SendSmsToOwnersWithoutApp": false,
"Sms": { "Enabled": false, "Provider": "JORMALL", "SenderId": "Nafith" }
}
}
},
// Primary connection = NAFITHTCS schema; NtpSchema = NTP schema (both required). Real values go in appsettings.Local.json / env vars
// (ConnectionStrings__NAFITHTCS, ConnectionStrings__NtpSchema). Option A - full connection strings (take priority):
"ConnectionStrings": {

View File

@ -88,9 +88,37 @@ public sealed class AutoCallOptions
/// <summary>Mobile notifications (legacy NTP.components.MobileNotifications.PrepareNotificationMessage).</summary>
public sealed class NotificationOptions
{
/// <summary>Off by default: a switched-on environment pushes to the real devices found in USERDEVICEINFO.</summary>
public bool Enabled { get; set; }
public string Url { get; set; } = string.Empty;
/// <summary>?wsdl address of the legacy push web service (backend/common/MobileNotification.cfc, operation SendFromCF9). It sends the push
/// (OneSignal) and writes MOBILENOTIFICATIONSLOG itself, so V2 only has to call it with the same arguments as legacy.</summary>
public string PushUrl { get; set; } = string.Empty;
public int TimeoutSeconds { get; set; } = 15;
/// <summary>Legacy application.SEND_SMS_GN_DIST: an SMS (with the app download link) goes to a truck owner / driver who has an account
/// but no app installed, when the truck is distributed. 0 in development and QA, 1 in production.</summary>
public bool SendSmsToOwnersWithoutApp { get; set; }
/// <summary>App download link added to that SMS (legacy hard-coded http://onelink.to/bhbrvb).</summary>
public string AppLink { get; set; } = "http://onelink.to/bhbrvb";
public SmsOptions Sms { get; set; } = new();
}
/// <summary>SMS provider (legacy NTP.components.SMS; application.SEND_SMS and application.SMS_PROVIDER). UserName / Password are secrets: environment variables only.</summary>
public sealed class SmsOptions
{
/// <summary>Legacy application.SEND_SMS = 'enabled'.</summary>
public bool Enabled { get; set; }
/// <summary>JORMALL (josms.net) or UNIFONIC. UNVERIFIED for this application: the sibling AqabaTCS app uses JorMall.</summary>
public string Provider { get; set; } = "JORMALL";
public string SenderId { get; set; } = "Nafith";
public string UserName { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
}
/// <summary>External weighbridge database (legacy datasource GrainsWeighbridge, table CARGO).</summary>

View File

@ -0,0 +1,59 @@
namespace NTP.Application.Grains.Permits;
/// <summary>NOTIFICATIONMESSAGETEMPLATE row (title and text with VAR1..VARn placeholders), looked up by TYPE.</summary>
public sealed class NotificationTemplateRow
{
public long Id { get; set; }
public string? Title { get; set; }
public string? Message { get; set; }
}
/// <summary>USERDEVICEINFO row of an ACTIVE device.</summary>
public sealed class DeviceRow
{
public string? FcmToken { get; set; }
public string? Os { get; set; }
}
/// <summary>Phone number and company (TCSCAC) of a registered truck.</summary>
public sealed class TruckContactRow
{
public string? Phone { get; set; }
public long? Scac { get; set; }
}
/// <summary>One push message to one device (the legacy SendNotificationToFirebase arguments).</summary>
public sealed record PushMessage(string Token, string Message, string Title, long UserId, string Os, long TemplateId, string Phone, string Tn);
/// <summary>Reads for the mobile notifications (legacy NTP.components.MobileNotifications): users, devices, templates, SMS log.</summary>
public interface INotificationRepository
{
Task<NotificationTemplateRow?> GetTemplateAsync(string type, CancellationToken ct = default);
/// <summary>NTPUSERS ids with this role and the given mobile number, exact login, or login containing <paramref name="loginContains"/> (case-insensitive).</summary>
Task<IReadOnlyList<long>> FindUserIdsAsync(string roleCode, string? mobile, string? login, string? loginContains, CancellationToken ct = default);
Task<IReadOnlyList<DeviceRow>> GetActiveDevicesAsync(long userId, CancellationToken ct = default);
/// <summary>The GN truck that is not revoked: its owner / driver phone and its company.</summary>
Task<TruckContactRow?> GetTruckContactAsync(string tn, CancellationToken ct = default);
/// <summary>Login of the active dispatcher (role DISP) of a company.</summary>
Task<string?> GetCompanyDispatcherLoginAsync(long scac, CancellationToken ct = default);
Task InsertSmsLogAsync(string userLogin, string mobile, string status, string request, string? response, string provider, string serviceType,
CancellationToken ct = default);
}
/// <summary>The legacy push web service (backend/common/MobileNotification.cfc, SendFromCF9) which sends the push and keeps the MOBILENOTIFICATIONSLOG row.</summary>
public interface IPushGatewayService
{
Task<bool> SendAsync(PushMessage message, CancellationToken ct = default);
}
/// <summary>SMS provider (legacy NTP.components.SMS.sendSMS); also writes USER_SMS_LOGS.</summary>
public interface ISmsGatewayService
{
/// <param name="mobile">International format with a leading plus, e.g. +9627...</param>
Task SendAsync(string mobile, string text, string userId, string serviceType, CancellationToken ct = default);
}

View File

@ -0,0 +1,77 @@
using System.Collections;
using System.Globalization;
namespace NTP.Application.Grains.Permits;
/// <summary>Pure rules of the mobile notifications (legacy MobileNotifications.cfc), kept apart so they can be tested.</summary>
public static class NotificationRules
{
/// <summary>Template types (NOTIFICATIONMESSAGETEMPLATE.TYPE) used by the grains screens.</summary>
public const string DistributeOwners = "DISTRIBUTE_PACKED_BULK_OWNERS";
public const string DistributeOwnersCompanies = "DISTRIBUTE_PACKED_BULK_OWNERS_COMPANIES";
public const string DistributeCompanies = "DISTRIBUTE_PACKED_BULK_COMP";
public const string ConfirmPn = "CONFIRM_PN";
public const string PhoneReject = "PHONE_REJECT";
public const string DelayPn = "DELAY_PN";
public const string SmsWithoutApp = "DISTRIBUTE_GRAINS_SMS_TO_USER_WITHNO_APP";
/// <summary>Driver and truck-owner app accounts are found by the truck's phone number.</summary>
public static readonly string[] PhoneRoles = ["DRVR", "TRKOWNER"];
/// <summary>Company dispatchers (role DISP) are found by a login that contains {SCAC}DSP.</summary>
public const string DispatcherRole = "DISP";
/// <summary>
/// ColdFusion <c>Replace(msg, 'VAR1', value)</c> for VAR1..VARn: each placeholder is replaced once (first occurrence), in order.
/// </summary>
public static string Fill(string template, params object?[] values)
{
var text = template;
for (var i = 0; i < values.Length; i++)
{
var key = "VAR" + (i + 1).ToString(CultureInfo.InvariantCulture);
var at = text.IndexOf(key, StringComparison.Ordinal);
if (at >= 0) text = string.Concat(text.AsSpan(0, at), Text(values[i]), text.AsSpan(at + key.Length));
}
return text;
}
/// <summary>Value as the legacy string concatenation would show it (dates as dd/MM/yyyy, no culture dependence).</summary>
public static string Text(object? v) => v switch
{
null => string.Empty,
string s => s,
DateTime d => d.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture),
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
_ => v.ToString() ?? string.Empty
};
/// <summary>SMS_toUsersWithNoMobileApplication: 0791234567 -> +962791234567 (mid(phone, 2, 15)); a number without a leading 0 only gets the prefix.</summary>
public static string SmsNumber(string phone)
{
var p = phone.Trim();
return p.StartsWith('0') ? "+962" + (p.Length > 16 ? p[1..16] : p[1..]) : "+962" + p;
}
/// <summary>The message plus the app download link, as SMS_toUsersWithNoMobileApplication builds it.</summary>
public static string SmsText(string template, string appLink) => template + "، للتفاصيل الرجاء الضغط على الرابط" + appLink;
/// <summary>Items of NOTIFICATIONARY as string maps (the callers pass dictionaries of mixed value types).</summary>
public static IReadOnlyList<IReadOnlyDictionary<string, string>> Entries(IReadOnlyDictionary<string, object?> payload)
{
var list = new List<IReadOnlyDictionary<string, string>>();
if (!payload.TryGetValue("NOTIFICATIONARY", out var raw) || raw is not IEnumerable items || raw is string) return list;
foreach (var item in items)
{
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (item is IEnumerable<KeyValuePair<string, object?>> pairs)
foreach (var (k, v) in pairs) map[k] = Text(v);
list.Add(map);
}
return list;
}
public static string Get(IReadOnlyDictionary<string, string> map, string key) => map.TryGetValue(key, out var v) ? v : string.Empty;
public static string Get(IReadOnlyDictionary<string, object?> map, string key) => map.TryGetValue(key, out var v) ? Text(v) : string.Empty;
}

View File

@ -56,6 +56,9 @@ public static class DependencyInjection
services.AddSingleton<IJobRunner, JobRunner>();
services.AddHostedService<JobSchedulerWorker>();
// mobile notifications run in the background in their own scope (see MobileNotificationGatewayService)
services.AddScoped<NTP.Infrastructure.Grains.NotificationDispatcher>();
// Convention: every concrete *Repository / *Service in this assembly is registered against I{Name} (scoped).
// Do NOT add per-table lines here.
services.AddConventionalServices(typeof(DependencyInjection).Assembly);

View File

@ -116,32 +116,6 @@ internal sealed class TcsPermitGatewayService(IGrainsPermitsSettingsService sett
}
}
/// <summary>Mobile push notifications (legacy NTP.components.MobileNotifications). POSTs {template, payload} JSON to the configured URL.</summary>
internal sealed class MobileNotificationGatewayService(IGrainsPermitsSettingsService settings, ILogger<MobileNotificationGatewayService> logger)
: IMobileNotificationGatewayService
{
private static readonly HttpClient Http = new();
public async Task SendAsync(string template, IReadOnlyDictionary<string, object?> 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);
}
}
}
/// <summary>Auto dialer / IVR (GrainsFactoryWeb.autoCallService2 and callAPI).</summary>
internal sealed class AutoCallGatewayService(IGrainsPermitsSettingsService settings, ILogger<AutoCallGatewayService> logger)
: IAutoCallGatewayService

View File

@ -0,0 +1,276 @@
using System.Security;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NTP.Application.Abstractions;
using NTP.Application.Grains.Permits;
namespace NTP.Infrastructure.Grains;
/// <summary>
/// Entry point of the mobile notifications (legacy NTP.components.MobileNotifications.PrepareNotificationMessage). Like legacy (a cfthread)
/// the work runs in the background in its own scope, so a distribution of hundreds of trucks does not wait for the pushes, and a failure
/// never reaches the business operation.
/// </summary>
internal sealed class MobileNotificationGatewayService(IGrainsPermitsSettingsService settings, IServiceScopeFactory scopes, ILogger<MobileNotificationGatewayService> logger)
: IMobileNotificationGatewayService
{
public Task SendAsync(string template, IReadOnlyDictionary<string, object?> payload, CancellationToken ct = default)
{
var o = settings.Value.Notifications;
if (!o.Enabled || string.IsNullOrWhiteSpace(o.PushUrl)) return Task.CompletedTask;
_ = Task.Run(async () =>
{
try
{
using var scope = scopes.CreateScope();
await scope.ServiceProvider.GetRequiredService<NotificationDispatcher>().RunAsync(template, payload, CancellationToken.None);
}
catch (Exception ex)
{
logger.LogWarning(ex, "Notification {Template} failed", template);
}
}, CancellationToken.None);
return Task.CompletedTask;
}
}
/// <summary>
/// Calls <c>SendFromCF9</c> of the legacy push web service with the arguments the legacy NTP application sent
/// (CF9Param = JSON of ReceiverType, FCMToken, Message, Title, UserId, OS, MSG_TEMPLATE_ID, LetterId, phoneNumber, tn).
/// The service pushes to OneSignal and writes MOBILENOTIFICATIONSLOG, so V2 does not hold the push provider key.
/// </summary>
internal sealed partial class PushGatewayService(IGrainsPermitsSettingsService settings, ILogger<PushGatewayService> logger) : IPushGatewayService
{
private static readonly HttpClient Http = new();
private static string? _namespace; // targetNamespace of the service, read once from its WSDL
public async Task<bool> SendAsync(PushMessage m, CancellationToken ct = default)
{
var o = settings.Value.Notifications;
if (!o.Enabled || string.IsNullOrWhiteSpace(o.PushUrl)) return false;
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds)));
var endpoint = o.PushUrl.EndsWith("?wsdl", StringComparison.OrdinalIgnoreCase) ? o.PushUrl[..^"?wsdl".Length] : o.PushUrl;
var ns = await NamespaceAsync(o.PushUrl, cts.Token);
var param = JsonSerializer.Serialize(new Dictionary<string, string>
{
["ReceiverType"] = "DEVICEID", ["FCMToken"] = m.Token, ["Message"] = m.Message, ["Title"] = m.Title,
["UserId"] = m.UserId.ToString(System.Globalization.CultureInfo.InvariantCulture), ["OS"] = m.Os,
["MSG_TEMPLATE_ID"] = m.TemplateId.ToString(System.Globalization.CultureInfo.InvariantCulture),
["LetterId"] = "0", ["phoneNumber"] = m.Phone, ["tn"] = m.Tn
});
var envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soapenv:Body>"
+ $"<ns:SendFromCF9 xmlns:ns=\"{SecurityElement.Escape(ns)}\" soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
+ $"<CF9Param xsi:type=\"xsd:string\">{SecurityElement.Escape(param)}</CF9Param></ns:SendFromCF9></soapenv:Body></soapenv:Envelope>";
using var req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new StringContent(envelope, Encoding.UTF8, "text/xml") };
req.Headers.TryAddWithoutValidation("SOAPAction", "\"\"");
using var res = await Http.SendAsync(req, cts.Token);
if (!res.IsSuccessStatusCode)
{
logger.LogWarning("Push service answered {Status} for user {UserId}", (int)res.StatusCode, m.UserId);
return false;
}
return true;
}
catch (Exception ex) when (!ct.IsCancellationRequested) // includes our own timeout
{
logger.LogWarning(ex, "Push service unreachable (user {UserId})", m.UserId);
return false;
}
}
private static async Task<string> NamespaceAsync(string wsdlUrl, CancellationToken ct)
{
if (_namespace is { } known) return known;
var wsdl = await Http.GetStringAsync(wsdlUrl, ct);
var match = TargetNamespace().Match(wsdl);
if (!match.Success) throw new InvalidOperationException("The push service WSDL has no targetNamespace");
return _namespace = match.Groups[1].Value;
}
[GeneratedRegex("targetNamespace\\s*=\\s*\"([^\"]+)\"")]
private static partial Regex TargetNamespace();
}
/// <summary>
/// SMS (legacy NTP.components.SMS.sendSMS): JorMall (josms.net) or Unifonic over HTTP GET, then a USER_SMS_LOGS row.
/// Nothing is sent unless Sms:Enabled (legacy application.SEND_SMS = 'enabled') and the account is configured.
/// The provider URL carries the account password, so it is never logged.
/// </summary>
internal sealed class SmsGatewayService(IGrainsPermitsSettingsService settings, INotificationRepository repository, ILogger<SmsGatewayService> logger)
: ISmsGatewayService
{
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(30) };
public async Task SendAsync(string mobile, string text, string userId, string serviceType, CancellationToken ct = default)
{
var o = settings.Value.Notifications.Sms;
if (!o.Enabled) return;
if (string.IsNullOrWhiteSpace(o.UserName) || string.IsNullOrWhiteSpace(o.Password))
{
logger.LogWarning("SMS is enabled but Grains:Permits:Notifications:Sms:UserName / Password are not set");
return;
}
var provider = o.Provider.Trim().ToUpperInvariant();
var number = mobile.TrimStart('+'); // both providers take the number without the plus
var msg = Uri.EscapeDataString(text);
string url;
switch (provider)
{
case "UNIFONIC":
url = $"http://api.unifonic.com/wrapper/sendSMS.php?userid={Uri.EscapeDataString(o.UserName)}&password={Uri.EscapeDataString(o.Password)}"
+ $"&msg={msg}&to={number}&sender={Uri.EscapeDataString(o.SenderId)}&encoding=UTF8";
break;
case "JORMALL":
url = $"https://www.josms.net/SMSServices/Clients/Prof/SingleSMS_General/SMSService.asmx/SendSMS?senderid={Uri.EscapeDataString(o.SenderId)}"
+ $"&numbers={number}&accname={Uri.EscapeDataString(o.UserName)}&AccPass={Uri.EscapeDataString(o.Password)}&msg={msg}&id=";
break;
default:
logger.LogWarning("Unknown SMS provider {Provider}", provider);
return;
}
var status = "FAIL";
string? response = null;
try
{
using var res = await Http.GetAsync(url, ct);
response = await res.Content.ReadAsStringAsync(ct);
status = res.IsSuccessStatusCode ? "SUCCESS" : "FAIL";
}
catch (Exception ex) when (!ct.IsCancellationRequested)
{
response = ex.GetType().Name; // the message can contain the request URL, which holds the password
logger.LogWarning("SMS to user {UserId} failed ({Reason})", userId, ex.GetType().Name);
}
try { await repository.InsertSmsLogAsync(userId, mobile, status, text, response, provider, serviceType, ct); }
catch (Exception ex) when (!ct.IsCancellationRequested) { logger.LogWarning(ex, "SMS log row could not be written"); }
}
}
/// <summary>The legacy flow of each template: who is notified, the VAR1..VARn values and the SMS for users without the app.</summary>
public sealed class NotificationDispatcher(
INotificationRepository repository,
IPushGatewayService push,
ISmsGatewayService sms,
IGrainsPermitsSettingsService settings,
ISystemErrorLogger systemErrors,
ILogger<NotificationDispatcher> logger)
{
public async Task RunAsync(string template, IReadOnlyDictionary<string, object?> payload, CancellationToken ct)
{
try
{
var info = await repository.GetTemplateAsync(template, ct);
if (info is null) { logger.LogWarning("Notification template {Template} is not in NOTIFICATIONMESSAGETEMPLATE", template); return; }
switch (template)
{
case NotificationRules.ConfirmPn:
await ToPhoneUsersAsync(info, NotificationRules.Get(payload, "MOBILE"), tn: "0", smsFallback: false,
[NotificationRules.Get(payload, "TN"), NotificationRules.Get(payload, "PN"), NotificationRules.Get(payload, "TT"), NotificationRules.Get(payload, "ORDERDATE")], ct);
break;
case NotificationRules.PhoneReject:
case NotificationRules.DelayPn:
await ToPhoneUsersAsync(info, NotificationRules.Get(payload, "MOBILE"), tn: "0", smsFallback: false,
[NotificationRules.Get(payload, "TN"), NotificationRules.Get(payload, "TT"), NotificationRules.Get(payload, "NUMOFEXPIRYDAY"), NotificationRules.Get(payload, "EXPIRYDATE")], ct);
break;
case NotificationRules.DistributeOwners:
foreach (var e in NotificationRules.Entries(payload))
{
var tn = NotificationRules.Get(e, "TN");
var phone = (await repository.GetTruckContactAsync(tn, ct))?.Phone ?? string.Empty;
await ToPhoneUsersAsync(info, phone, tn, smsFallback: true,
[tn, NotificationRules.Get(e, "TT"), NotificationRules.Get(e, "LOCATION"), NotificationRules.Get(e, "ORDERDATE"), NotificationRules.Get(e, "SHIFT")], ct);
}
break;
case NotificationRules.DistributeOwnersCompanies:
foreach (var e in NotificationRules.Entries(payload))
{
var tn = NotificationRules.Get(e, "TN");
if ((await repository.GetTruckContactAsync(tn, ct))?.Scac is not long scac) continue;
if (await repository.GetCompanyDispatcherLoginAsync(scac, ct) is not { Length: > 0 } login) continue;
var users = await repository.FindUserIdsAsync(NotificationRules.DispatcherRole, mobile: null, login: login, loginContains: null, ct);
foreach (var user in users)
await PushToUserAsync(info, user, tn, phone: "0",
NotificationRules.Fill(info.Message ?? string.Empty, tn, NotificationRules.Get(e, "TT"), NotificationRules.Get(e, "LOCATION"),
NotificationRules.Get(e, "ORDERDATE"), NotificationRules.Get(e, "SHIFT")), ct);
}
break;
case NotificationRules.DistributeCompanies:
var type = NotificationRules.Get(payload, "TT");
foreach (var (key, count) in payload)
{
if (key == "TT") continue;
var users = await repository.FindUserIdsAsync(NotificationRules.DispatcherRole, mobile: null, login: null, loginContains: key + "DSP", ct);
foreach (var user in users)
await PushToUserAsync(info, user, tn: "0", phone: "0", NotificationRules.Fill(info.Message ?? string.Empty, count, type), ct);
}
break;
default:
logger.LogWarning("Notification template {Template} has no flow in V2", template);
break;
}
}
catch (Exception ex) when (!ct.IsCancellationRequested)
{
logger.LogWarning(ex, "Notification {Template} failed", template);
try { await systemErrors.LogAsync(ex, "SYSTEM", null, null, "notification " + template); } catch { /* logging must not throw */ }
}
}
/// <summary>Driver and truck-owner accounts of a phone number: push to their devices; optionally an SMS when an account has no device.</summary>
private async Task ToPhoneUsersAsync(NotificationTemplateRow info, string phone, string tn, bool smsFallback, object?[] values, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(phone)) return;
var text = NotificationRules.Fill(info.Message ?? string.Empty, values);
foreach (var role in NotificationRules.PhoneRoles)
{
foreach (var user in await repository.FindUserIdsAsync(role, mobile: phone, login: null, loginContains: null, ct))
{
var sent = await PushToUserAsync(info, user, tn, phone, text, ct);
if (!sent.HadDevice && smsFallback && settings.Value.Notifications.SendSmsToOwnersWithoutApp)
await SendAppSmsAsync(phone, user, tn, ct);
}
}
}
private async Task<(bool HadDevice, bool Sent)> PushToUserAsync(NotificationTemplateRow info, long userId, string tn, string phone, string text, CancellationToken ct)
{
var devices = await repository.GetActiveDevicesAsync(userId, ct);
var any = false;
var sent = false;
foreach (var d in devices)
{
if (string.IsNullOrWhiteSpace(d.FcmToken)) continue;
any = true;
sent |= await push.SendAsync(new PushMessage(d.FcmToken, text, info.Title ?? string.Empty, userId, d.Os ?? string.Empty, info.Id, phone, tn), ct);
}
return (any, sent);
}
/// <summary>SMS_toUsersWithNoMobileApplication: the SMS template with the truck number and the app link.</summary>
private async Task SendAppSmsAsync(string phone, long userId, string tn, CancellationToken ct)
{
var smsTemplate = await repository.GetTemplateAsync(NotificationRules.SmsWithoutApp, ct);
if (smsTemplate is null) { logger.LogWarning("SMS template {Template} is not in NOTIFICATIONMESSAGETEMPLATE", NotificationRules.SmsWithoutApp); return; }
var text = NotificationRules.SmsText(NotificationRules.Fill(smsTemplate.Message ?? string.Empty, tn), settings.Value.Notifications.AppLink);
await sms.SendAsync(NotificationRules.SmsNumber(phone), text, userId.ToString(System.Globalization.CultureInfo.InvariantCulture), "UNIFONIC", ct);
}
}

View File

@ -0,0 +1,75 @@
using Microsoft.Extensions.Logging;
using NTP.Application.Grains.Permits;
namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits;
/// <summary>
/// Reads and writes of MobileNotifications.cfc. The tables NOTIFICATIONMESSAGETEMPLATE, USERDEVICEINFO, NTPUSERS, COMPANIES and USER_SMS_LOGS are
/// in the NTP schema (this base); NTP_TRUCKS is in the primary NAFITHTCS schema (<c>Primary</c>).
/// </summary>
internal sealed class NotificationRepository(INtpDbSession session, IDbSession primarySession, ILogger<NotificationRepository> logger)
: NtpRepositoryBase(session, logger), INotificationRepository
{
private PrimaryAccess Primary { get; } = new(primarySession, logger);
private sealed class PrimaryAccess(IDbSession s, ILogger l) : OracleRepositoryBase(s, l)
{
public Task<T?> FirstAsync<T>(string sql, object? p, CancellationToken ct) => QueryFirstAsync<T>(sql, p, ct);
}
public Task<NotificationTemplateRow?> GetTemplateAsync(string type, CancellationToken ct = default) =>
QueryFirstAsync<NotificationTemplateRow>("""
SELECT ID AS Id, TITLE AS Title, MESSAGE AS Message FROM NOTIFICATIONMESSAGETEMPLATE WHERE TYPE = :Type ORDER BY ID
""", new { Type = type }, ct);
public async Task<IReadOnlyList<long>> FindUserIdsAsync(string roleCode, string? mobile, string? login, string? loginContains, CancellationToken ct = default)
{
// legacy getLoginInfo: every given field must match, case-insensitively; an empty value matches nothing (Oracle '' is NULL)
var sql = "SELECT ID FROM NTPUSERS WHERE UPPER(ROLECODE) = UPPER(:Role)";
var p = new Dapper.DynamicParameters();
p.Add("Role", roleCode);
if (mobile is not null) { sql += " AND UPPER(MOBILE) = UPPER(:Mobile)"; p.Add("Mobile", mobile); }
if (login is not null) { sql += " AND UPPER(LOGIN) = UPPER(:Login)"; p.Add("Login", login); }
if (loginContains is not null) { sql += " AND UPPER(LOGIN) LIKE '%' || UPPER(:LoginPart) || '%'"; p.Add("LoginPart", loginContains); }
sql += " ORDER BY ID";
return await QueryAsync<long>(sql, p, ct);
}
public Task<IReadOnlyList<DeviceRow>> GetActiveDevicesAsync(long userId, CancellationToken ct = default) =>
QueryAsync<DeviceRow>("""
SELECT FCMTOKEN AS FcmToken, OS AS Os FROM USERDEVICEINFO WHERE USERID = :UserId AND STATUSCODE = 'ACTIVE' ORDER BY ID
""", new { UserId = userId }, ct);
public Task<TruckContactRow?> GetTruckContactAsync(string tn, CancellationToken ct = default) =>
Primary.FirstAsync<TruckContactRow>("""
SELECT * FROM (
SELECT TO_CHAR(t.PHONENUMBER) AS Phone, t.TCSCAC AS Scac
FROM NTP_TRUCKS t
WHERE t.TN = :Tn AND t.DOMAIN = 'GN' AND t.STATUSCODE NOT IN ('RVKD')
ORDER BY t.ID DESC
) WHERE ROWNUM = 1
""", new { Tn = tn }, ct);
public Task<string?> GetCompanyDispatcherLoginAsync(long scac, CancellationToken ct = default) =>
QueryFirstAsync<string>("""
SELECT * FROM (
SELECT n.LOGIN
FROM NTPUSERS n, COMPANIES c
WHERE c.SCAC = :Scac AND n.COMPANYID = c.ID AND n.ROLECODE = 'DISP' AND n.STATUS = 1
ORDER BY n.ID
) WHERE ROWNUM = 1
""", new { Scac = scac }, ct);
public Task InsertSmsLogAsync(string userLogin, string mobile, string status, string request, string? response, string provider, string serviceType,
CancellationToken ct = default) =>
ExecuteAsync("""
INSERT INTO USER_SMS_LOGS (ID, SERVICETYPE, USERLOGIN, MOBILENO, DATETIME, STATUS, MSG_REQUEST, MSG_RESPONSE, SMSPROVIDER)
VALUES (SEQ_SMS_LOGS.NEXTVAL, :ServiceType, :UserLogin, :Mobile, SYSDATE, :Status, :Request, :Response, :Provider)
""", new
{
ServiceType = serviceType, UserLogin = userLogin, Mobile = mobile, Status = status,
Request = Cut(request, 1500), Response = Cut(response, 4000), Provider = provider
}, ct);
private static string? Cut(string? s, int max) => s is { Length: var n } && n > max ? s[..max] : s;
}

View File

@ -0,0 +1,199 @@
using Microsoft.Extensions.Logging.Abstractions;
using NTP.Application.Abstractions;
using NTP.Application.Grains.Permits;
using NTP.Infrastructure.Grains;
namespace NTP.Tests;
public class NotificationRulesTests
{
[Fact]
public void Fill_replaces_each_placeholder_once_in_order()
{
Assert.Equal("شاحنة 1234 - قمح - عقبة", NotificationRules.Fill("شاحنة VAR1 - VAR2 - VAR3", "1234", "قمح", "عقبة"));
// ColdFusion Replace() without scope changes only the first occurrence
Assert.Equal("1234 VAR1", NotificationRules.Fill("VAR1 VAR1", "1234"));
}
[Fact]
public void Sms_number_follows_the_legacy_prefix_rule()
{
Assert.Equal("+962791234567", NotificationRules.SmsNumber("0791234567"));
Assert.Equal("+962791234567", NotificationRules.SmsNumber("791234567"));
}
[Fact]
public void Sms_text_adds_the_app_link()
{
Assert.Equal("نص، للتفاصيل الرجاء الضغط على الرابطhttp://x", NotificationRules.SmsText("نص", "http://x"));
}
[Fact]
public void Entries_reads_dictionaries_of_mixed_types()
{
var payload = new Dictionary<string, object?>
{
["NOTIFICATIONARY"] = new List<IReadOnlyDictionary<string, object?>>
{
new Dictionary<string, object?> { ["TN"] = "12345", ["SHIFT"] = 2L, ["ORDERDATE"] = new DateTime(2026, 1, 5) }
}
};
var e = Assert.Single(NotificationRules.Entries(payload));
Assert.Equal("12345", NotificationRules.Get(e, "tn"));
Assert.Equal("2", NotificationRules.Get(e, "SHIFT"));
Assert.Equal("05/01/2026", NotificationRules.Get(e, "ORDERDATE"));
}
}
public class NotificationDispatcherTests
{
private sealed class FakeRepo : INotificationRepository
{
public Dictionary<(string Role, string? Mobile, string? Login, string? Part), long[]> Users = new();
public Dictionary<long, DeviceRow[]> Devices = new();
public string Phone = "0791234567";
public long? Scac = 45;
public string? DispatcherLogin = "045DSP1";
public List<string> TemplatesAsked = [];
public Task<NotificationTemplateRow?> GetTemplateAsync(string type, CancellationToken ct = default)
{
TemplatesAsked.Add(type);
return Task.FromResult<NotificationTemplateRow?>(new NotificationTemplateRow { Id = 7, Title = "عنوان", Message = type == NotificationRules.SmsWithoutApp ? "الشاحنة VAR1" : "VAR1 / VAR2 / VAR3 / VAR4 / VAR5" });
}
public Task<IReadOnlyList<long>> FindUserIdsAsync(string roleCode, string? mobile, string? login, string? loginContains, CancellationToken ct = default) =>
Task.FromResult<IReadOnlyList<long>>(Users.GetValueOrDefault((roleCode, mobile, login, loginContains), []));
public Task<IReadOnlyList<DeviceRow>> GetActiveDevicesAsync(long userId, CancellationToken ct = default) =>
Task.FromResult<IReadOnlyList<DeviceRow>>(Devices.GetValueOrDefault(userId, []));
public Task<TruckContactRow?> GetTruckContactAsync(string tn, CancellationToken ct = default) =>
Task.FromResult<TruckContactRow?>(new TruckContactRow { Phone = Phone, Scac = Scac });
public Task<string?> GetCompanyDispatcherLoginAsync(long scac, CancellationToken ct = default) => Task.FromResult(DispatcherLogin);
public Task InsertSmsLogAsync(string userLogin, string mobile, string status, string request, string? response, string provider, string serviceType, CancellationToken ct = default) => Task.CompletedTask;
}
private sealed class FakePush : IPushGatewayService
{
public List<PushMessage> Sent = [];
public Task<bool> SendAsync(PushMessage message, CancellationToken ct = default) { Sent.Add(message); return Task.FromResult(true); }
}
private sealed class FakeSms : ISmsGatewayService
{
public List<(string Mobile, string Text, string User)> Sent = [];
public Task SendAsync(string mobile, string text, string userId, string serviceType, CancellationToken ct = default) { Sent.Add((mobile, text, userId)); return Task.CompletedTask; }
}
private sealed class Settings(bool sms) : IGrainsPermitsSettingsService
{
public GrainsPermitsOptions Value { get; } = new()
{
Notifications = new NotificationOptions { Enabled = true, PushUrl = "x", SendSmsToOwnersWithoutApp = sms, AppLink = "http://link" }
};
}
private sealed class NoErrors : ISystemErrorLogger
{
public Task LogAsync(Exception exception, string? userId, string? ipAddress, string? browser, string? requestInfo) => Task.CompletedTask;
}
private static (NotificationDispatcher d, FakeRepo repo, FakePush push, FakeSms sms) Make(bool smsFlag)
{
var repo = new FakeRepo();
var push = new FakePush();
var sms = new FakeSms();
return (new NotificationDispatcher(repo, push, sms, new Settings(smsFlag), new NoErrors(), NullLogger<NotificationDispatcher>.Instance), repo, push, sms);
}
private static Dictionary<string, object?> OwnerPayload() => new()
{
["NOTIFICATIONARY"] = new[] { new Dictionary<string, object?> { ["TN"] = "5555", ["TT"] = "قمح", ["LOCATION"] = "صومعة", ["ORDERDATE"] = "05/01/2026", ["SHIFT"] = "1" } }
};
[Fact]
public async Task Owner_distribution_pushes_to_the_devices_of_driver_and_owner_accounts()
{
var (d, repo, push, sms) = Make(smsFlag: true);
repo.Users[("DRVR", "0791234567", null, null)] = [11];
repo.Users[("TRKOWNER", "0791234567", null, null)] = [12];
repo.Devices[11] = [new DeviceRow { FcmToken = "tok-a", Os = "ANDROID" }, new DeviceRow { FcmToken = "tok-b", Os = "IOS" }];
repo.Devices[12] = [new DeviceRow { FcmToken = "tok-c", Os = "ANDROID" }];
await d.RunAsync(NotificationRules.DistributeOwners, OwnerPayload(), CancellationToken.None);
Assert.Equal(["tok-a", "tok-b", "tok-c"], push.Sent.Select(m => m.Token));
Assert.All(push.Sent, m => Assert.Equal("5555 / قمح / صومعة / 05/01/2026 / 1", m.Message));
Assert.Empty(sms.Sent); // everybody has the app
}
[Fact]
public async Task Account_without_a_device_gets_the_sms_only_when_the_flag_is_on()
{
var on = Make(smsFlag: true);
on.repo.Users[("DRVR", "0791234567", null, null)] = [11];
await on.d.RunAsync(NotificationRules.DistributeOwners, OwnerPayload(), CancellationToken.None);
var sent = Assert.Single(on.sms.Sent);
Assert.Equal("+962791234567", sent.Mobile);
Assert.Equal("11", sent.User);
Assert.Equal("الشاحنة 5555، للتفاصيل الرجاء الضغط على الرابطhttp://link", sent.Text);
Assert.Empty(on.push.Sent);
var off = Make(smsFlag: false);
off.repo.Users[("DRVR", "0791234567", null, null)] = [11];
await off.d.RunAsync(NotificationRules.DistributeOwners, OwnerPayload(), CancellationToken.None);
Assert.Empty(off.sms.Sent);
}
[Fact]
public async Task No_account_for_the_phone_means_no_push_and_no_sms()
{
var (d, _, push, sms) = Make(smsFlag: true);
await d.RunAsync(NotificationRules.DistributeOwners, OwnerPayload(), CancellationToken.None);
Assert.Empty(push.Sent);
Assert.Empty(sms.Sent);
}
[Fact]
public async Task Company_distribution_goes_to_the_dispatchers_whose_login_contains_the_company_code()
{
var (d, repo, push, _) = Make(smsFlag: false);
repo.Users[("DISP", null, null, "045DSP")] = [21];
repo.Devices[21] = [new DeviceRow { FcmToken = "tok-d", Os = "ANDROID" }];
var payload = new Dictionary<string, object?> { ["045"] = 3, ["TT"] = "قمح" };
await d.RunAsync(NotificationRules.DistributeCompanies, payload, CancellationToken.None);
var m = Assert.Single(push.Sent);
Assert.Equal("3 / قمح / VAR3 / VAR4 / VAR5", m.Message);
Assert.Equal(21, m.UserId);
}
[Fact]
public async Task Manual_distribution_notifies_the_dispatcher_of_the_truck_company()
{
var (d, repo, push, sms) = Make(smsFlag: true);
repo.Users[("DISP", null, "045DSP1", null)] = [31];
repo.Devices[31] = [new DeviceRow { FcmToken = "tok-e", Os = "IOS" }];
await d.RunAsync(NotificationRules.DistributeOwnersCompanies, OwnerPayload(), CancellationToken.None);
Assert.Equal("tok-e", Assert.Single(push.Sent).Token);
Assert.Empty(sms.Sent); // dispatchers never get the SMS
}
[Fact]
public async Task Phone_confirmation_uses_the_mobile_of_the_payload()
{
var (d, repo, push, _) = Make(smsFlag: true);
repo.Users[("TRKOWNER", "0799999999", null, null)] = [41];
repo.Devices[41] = [new DeviceRow { FcmToken = "tok-f", Os = "ANDROID" }];
var payload = new Dictionary<string, object?> { ["MOBILE"] = "0799999999", ["TN"] = "7", ["PN"] = "P1", ["TT"] = "قمح", ["ORDERDATE"] = "06/01/2026" };
await d.RunAsync(NotificationRules.ConfirmPn, payload, CancellationToken.None);
Assert.Equal("7 / P1 / قمح / 06/01/2026 / VAR5", Assert.Single(push.Sent).Message);
}
}