using System.Globalization; using System.Text.Encodings.Web; using System.Text.Json; using NTP.Application.Refinery.Integrations; namespace NTP.Infrastructure.Integrations; /// /// 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. /// public static class DinarakProtocol { /// picCode values of the Jordanian wallet providers that are paid with the operation "Transfer" (RefinaryDinarakApi.cfc:132). 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"; /// Statuses of getTransferByMessageID that count as "already sent" (RefinaryDinarakApi.cfc:233). public static readonly string[] AcceptedStatuses = ["Success", "Processing", "New"]; private static readonly JsonWriterOptions Raw = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; private static string Write(Action body) { using var ms = new MemoryStream(); using (var w = new Utf8JsonWriter(ms, Raw)) body(w); return System.Text.Encoding.UTF8.GetString(ms.ToArray()); } /// Body of POST /token. 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(); }); /// Token request as it is kept in REFINERY_DINARAK_API_LOG: the legacy code stored the password there, this one does not. public static string BuildTokenRequestForLog(string userName) => BuildTokenRequest(userName, "***"); /// "Transfer" for a known wallet provider, otherwise "bank salary internal" (picCode of AliasResolve, case-insensitive). public static string OperationFor(string? picCode) => picCode is not null && TransferWalletTypes.Contains(picCode.Trim(), StringComparer.OrdinalIgnoreCase) ? TransferOperation : SalaryOperation; /// picCode of the AliasResolve answer, or null when the body is not the expected JSON (legacy: "Invalid Wallet"). 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; } } /// "352.1": the message id / reference of a trip (a decimal because ACTIVATE_WALLET_EXCHANGE adds 0.01). public static string FormatMessageId(decimal id) => id.ToString("0.##########", CultureInfo.InvariantCulture); /// /// 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. /// 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(); }); /// Same value check as legacy: |calculated - requested| rounded to 3 decimals must not exceed 0.001. 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(' ', '_'); /// Answer of POST /transfer/transfer: 200 + status.name Success = 000; other status = 102 (error text with underscores); HTTP error = 103. 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"); } } /// Answer of GET /transfer/transferByMessageID. A non-200 answer means "nothing found" (legacy: not accepted); StatusName "HTTP_{code}". 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); } } /// The access token of the POST /token answer, as the Authorization header value the legacy code built ("bearer {token}"), or null. 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; } } }