using System; using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; namespace OnlineSalesAutoCrop.CoreAPI.Models.Responses.Integrations; public class IntegrationCustLedgerHttpResponse { public string Company { get; set; } public string Customer_no { get; set; } public decimal Current_Balance { get; set; } public decimal Overdue_Amount { get; set; } } public class IntegrationMaterialStockHttpResponse { public string Plant { get; set; } public string Material { get; set; } public decimal Available_Stock { get; set; } public string UOM { get; set; } } // Reusable envelope for any SAP OData V2 collection response: { "d": { "results": [...] } } public sealed class SapODataResponse { [JsonPropertyName("d")] public SapODataResult D { get; set; } = default!; } public sealed class SapODataResult { [JsonPropertyName("results")] public List Results { get; set; } = new(); } public sealed class CustomerLedgerDto { [JsonPropertyName("company")] public string Company { get; set; } = string.Empty; [JsonPropertyName("customer_no")] public string CustomerNo { get; set; } = string.Empty; // stays string — SAP customer numbers can carry leading zeros [JsonPropertyName("current_balance")] [JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] public decimal CurrentBalance { get; set; } [JsonPropertyName("overdue_amount")] [JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] public decimal OverdueAmount { get; set; } [JsonPropertyName("currency")] public string Currency { get; set; } = string.Empty; [JsonPropertyName("overdue_date")] [JsonConverter(typeof(SapODataDateConverter))] public DateTime OverdueDate { get; set; } } public sealed class SapODataDateConverter : JsonConverter { // Matches "/Date(1783641600000)/" and the rarer offset form "/Date(1783641600000+0600)/" private static readonly Regex Pattern = new(@"/Date\((-?\d+)(?:[+-]\d{4})?\)/", RegexOptions.Compiled); public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var raw = reader.GetString(); if (string.IsNullOrEmpty(raw)) return default; var match = Pattern.Match(raw); if (!match.Success) throw new JsonException($"Unexpected SAP OData date format: '{raw}'"); var ms = long.Parse(match.Groups[1].Value); return DateTimeOffset.FromUnixTimeMilliseconds(ms).UtcDateTime; } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { var ms = new DateTimeOffset(value, TimeSpan.Zero).ToUnixTimeMilliseconds(); writer.WriteStringValue($"/Date({ms})/"); } }