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

142 lines
6.9 KiB
C#

using System.Globalization;
using System.Text.Encodings.Web;
using System.Text.Json;
using NTP.Application.Refinery.Integrations;
namespace NTP.Infrastructure.Integrations;
/// <summary>
/// The pure parts of legacy backend/common/RefinaryDinarakApi.cfc: request bodies, wallet type to operation mapping, response mapping and
/// the amount comparison. No I/O, so they are unit tested without a server.
/// </summary>
public static class DinarakProtocol
{
/// <summary>picCode values of the Jordanian wallet providers that are paid with the operation "Transfer" (RefinaryDinarakApi.cfc:132).</summary>
public static readonly string[] TransferWalletTypes =
["ZAINJOPX", "ORNGJOPX", "DNRKJOPX", "GDHAJOPX", "MEPSJOPX", "ALWPJOPX", "UWLTJOPX", "MDFTJOPX"];
public const string TransferOperation = "Transfer";
public const string SalaryOperation = "bank salary internal";
/// <summary>Statuses of getTransferByMessageID that count as "already sent" (RefinaryDinarakApi.cfc:233).</summary>
public static readonly string[] AcceptedStatuses = ["Success", "Processing", "New"];
private static readonly JsonWriterOptions Raw = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
private static string Write(Action<Utf8JsonWriter> body)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, Raw)) body(w);
return System.Text.Encoding.UTF8.GetString(ms.ToArray());
}
/// <summary>Body of POST /token.</summary>
public static string BuildTokenRequest(string userName, string password) => Write(w =>
{
w.WriteStartObject();
w.WriteString("username", userName);
w.WriteString("password", password);
w.WriteString("grant_type", "password");
w.WriteEndObject();
});
/// <summary>Token request as it is kept in REFINERY_DINARAK_API_LOG: the legacy code stored the password there, this one does not.</summary>
public static string BuildTokenRequestForLog(string userName) => BuildTokenRequest(userName, "***");
/// <summary>"Transfer" for a known wallet provider, otherwise "bank salary internal" (picCode of AliasResolve, case-insensitive).</summary>
public static string OperationFor(string? picCode) =>
picCode is not null && TransferWalletTypes.Contains(picCode.Trim(), StringComparer.OrdinalIgnoreCase) ? TransferOperation : SalaryOperation;
/// <summary>picCode of the AliasResolve answer, or null when the body is not the expected JSON (legacy: "Invalid Wallet").</summary>
public static string? ParsePicCode(string body)
{
try
{
using var doc = JsonDocument.Parse(body);
return doc.RootElement.TryGetProperty("picCode", out var p) && p.ValueKind == JsonValueKind.String ? p.GetString() : null;
}
catch (JsonException) { return null; }
}
/// <summary>"352.1": the message id / reference of a trip (a decimal because ACTIVATE_WALLET_EXCHANGE adds 0.01).</summary>
public static string FormatMessageId(decimal id) => id.ToString("0.##########", CultureInfo.InvariantCulture);
/// <summary>
/// Body of POST /transfer/transfer, same property order as the legacy struct. Description is " {loadingNumber}" (leading space as in
/// the legacy code); MessageId and Reference both carry the trip's Dinarak reference id.
/// </summary>
public static string BuildTransferRequest(string receiverName, decimal amount, string loadingNumber, decimal reference, string walletNumber, string operationName) =>
Write(w =>
{
var id = FormatMessageId(reference);
w.WriteStartObject();
w.WriteString("Name", receiverName);
w.WriteNumber("Amount", amount);
w.WriteString("Description", " " + loadingNumber);
w.WriteString("MessageId", id);
w.WriteString("Reference", id);
w.WriteString("ReceiverID", walletNumber);
w.WriteString("OperationName", operationName);
w.WriteStartArray("Conditions");
w.WriteStartObject();
w.WriteString("NationalId", string.Empty);
w.WriteEndObject();
w.WriteEndArray();
w.WriteEndObject();
});
/// <summary>Same value check as legacy: |calculated - requested| rounded to 3 decimals must not exceed 0.001.</summary>
public static bool AmountMatches(decimal calculated, decimal requested) =>
Math.Round(Math.Abs(calculated - requested), 3, MidpointRounding.AwayFromZero) <= 0.001m;
private static string Underscored(string? text) => (text ?? string.Empty).Replace(' ', '_');
/// <summary>Answer of POST /transfer/transfer: 200 + status.name Success = 000; other status = 102 (error text with underscores); HTTP error = 103.</summary>
public static DinarakTransferResult MapTransferResponse(int httpStatus, string body)
{
if (httpStatus != 200) return new("103", Underscored(body));
try
{
using var doc = JsonDocument.Parse(body);
var status = doc.RootElement.GetProperty("status");
var name = status.GetProperty("name").GetString();
if (string.Equals(name, "Success", StringComparison.Ordinal)) return new("000", "SUCCESS");
var error = status.TryGetProperty("errorMessage", out var e) && e.ValueKind == JsonValueKind.String ? e.GetString() : name;
return new("102", Underscored(error));
}
catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException)
{
return new("104", "SYSTEM_ERROR_INVALID_RESPONSE");
}
}
/// <summary>Answer of GET /transfer/transferByMessageID. A non-200 answer means "nothing found" (legacy: not accepted); StatusName "HTTP_{code}".</summary>
public static DinarakTransferStatus MapStatusResponse(int httpStatus, string body)
{
if (httpStatus != 200) return new(false, $"HTTP_{httpStatus}", body);
try
{
using var doc = JsonDocument.Parse(body);
var name = doc.RootElement.GetProperty("status").GetProperty("name").GetString();
return new(name is not null && AcceptedStatuses.Contains(name, StringComparer.Ordinal), name, body);
}
catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException)
{
return new(false, "ERROR", body);
}
}
/// <summary>The access token of the POST /token answer, as the Authorization header value the legacy code built ("bearer {token}"), or null.</summary>
public static string? ParseBearer(string body)
{
try
{
using var doc = JsonDocument.Parse(body);
return doc.RootElement.TryGetProperty("access_token", out var t) && t.ValueKind == JsonValueKind.String && !string.IsNullOrEmpty(t.GetString())
? "bearer " + t.GetString()
: null;
}
catch (JsonException) { return null; }
}
}