using System.Collections.Concurrent; using System.Globalization; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; namespace GuestOps.Web; public sealed class OhipTokens { readonly ConcurrentDictionary cache = new(); readonly SemaphoreSlim gate = new(1,1); public async Task Get(string hotel, OhipProfile profile, HttpClient http, CancellationToken ct) { var key = hotel + ":" + profile.Revision; await gate.WaitAsync(ct); try { if (cache.TryGetValue(key, out var hit) && hit.Until > DateTime.UtcNow) return hit.Token; foreach (var old in cache.Where(x => x.Value.Until <= DateTime.UtcNow).Select(x => x.Key)) cache.TryRemove(old, out _); using var request = new HttpRequestMessage(HttpMethod.Post, profile.BaseUrl.TrimEnd('/') + "/oauth/v1/tokens"); request.Headers.Authorization = new("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(profile.ClientId + ":" + profile.ClientSecret))); request.Headers.Add("x-app-key", profile.AppKey); if (profile.EnterpriseId.Length > 0) request.Headers.Add("enterpriseId", profile.EnterpriseId); request.Content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["scope"] = profile.Scope }); using var response = await http.SendAsync(request, ct); response.EnsureSuccessStatusCode(); using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct)); var token = json.RootElement.GetProperty("access_token").GetString(); if (string.IsNullOrWhiteSpace(token)) throw new PmsInvalid("OHIP did not issue an access token."); var seconds = json.RootElement.TryGetProperty("expires_in", out var expiry) && expiry.TryGetInt32(out var value) ? value : 60; cache[key] = (token, DateTime.UtcNow.AddSeconds(Math.Clamp(seconds - 60, 0, 3600))); return token; } finally { gate.Release(); } } } public sealed class OhipClient(HttpClient http, OhipTokens tokens) { static string Segment(string value) => Uri.EscapeDataString(value); static string Route(OhipProfile p) => "/rsv/v1/hotels/" + Segment(p.HotelCode) + "/reservations"; async Task Request(string hotel, OhipProfile p, HttpMethod method, string path, CancellationToken ct) { var request = new HttpRequestMessage(method, p.BaseUrl.TrimEnd('/') + path); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await tokens.Get(hotel, p, http, ct)); request.Headers.Add("x-app-key", p.AppKey); request.Headers.Add("x-hotelid", p.HotelCode); request.Headers.Accept.Add(new("application/json")); return request; } async Task Read(string hotel, OhipProfile p, string path, CancellationToken ct) { using var request = await Request(hotel, p, HttpMethod.Get, path, ct); using var response = await http.SendAsync(request, ct); response.EnsureSuccessStatusCode(); using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct)); return json.RootElement.Clone(); } static JsonElement[] Reservations(JsonElement root) { if (!root.TryGetProperty("reservations", out var r)) throw new PmsInvalid("OHIP returned an unsupported reservation response."); if (r.ValueKind == JsonValueKind.Object) { if (r.TryGetProperty("hasMore", out var more) && more.ValueKind == JsonValueKind.True) throw new PmsInvalid("The reservation lookup returned more results than can be safely matched."); r = r.GetProperty("reservation"); } return r.ValueKind == JsonValueKind.Array ? r.EnumerateArray().ToArray() : r.ValueKind == JsonValueKind.Object ? [r] : throw new PmsInvalid("No reservation returned."); } static string Text(JsonElement element, params string[] path) { foreach (var key in path) { if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty(key, out element)) return ""; } return element.ValueKind == JsonValueKind.String ? element.GetString()! : element.ValueKind == JsonValueKind.Number ? element.GetRawText() : ""; } static string Id(JsonElement r, string kind) { if (!r.TryGetProperty("reservationIdList", out var ids) || ids.ValueKind != JsonValueKind.Array) return ""; var matches = ids.EnumerateArray().Where(x => Text(x,"type") == kind).Select(x => Text(x,"id")).Distinct().ToArray(); return matches.Length == 1 ? matches[0] : ""; } public async Task Lookup(string hotel, OhipProfile p, string confirmation, CancellationToken ct) { if (!System.Text.RegularExpressions.Regex.IsMatch(confirmation, "^[a-zA-Z0-9-]{1,80}$")) throw new PmsInvalid("Enter the exact PMS confirmation number."); var json = await Read(hotel,p,Route(p)+"?confirmationNumberList="+Segment(confirmation)+"&limit=100",ct); var matches = Reservations(json).Where(r => Id(r,"Confirmation").Equals(confirmation,StringComparison.OrdinalIgnoreCase)).ToArray(); if (matches.Length != 1 || string.IsNullOrWhiteSpace(Id(matches[0],"Reservation"))) throw new PmsInvalid("No single exact reservation matched that confirmation. Check it in the PMS."); return await Fetch(hotel,p,Id(matches[0],"Reservation"),confirmation,ct); } public async Task Fetch(string hotel, OhipProfile p, string id, string confirmation, CancellationToken ct) { var json = await Read(hotel,p,Route(p)+"/"+Segment(id)+"?fetchInstructions=Reservation&fetchInstructions=Comments&fetchInstructions=TotalCostOfStay",ct); var rows = Reservations(json); if (rows.Length != 1 || Id(rows[0],"Reservation") != id || !Id(rows[0],"Confirmation").Equals(confirmation,StringComparison.OrdinalIgnoreCase) || Text(rows[0],"hotelId") != p.HotelCode) throw new PmsInvalid("OHIP reservation identity did not match this hotel's request."); var row = rows[0]; var arrival=Text(row,"roomStay","arrivalDate"); var departure=Text(row,"roomStay","departureDate"); if (!DateOnly.TryParseExact(arrival,"yyyy-MM-dd",CultureInfo.InvariantCulture,DateTimeStyles.None,out _) || !DateOnly.TryParseExact(departure,"yyyy-MM-dd",CultureInfo.InvariantCulture,DateTimeStyles.None,out _)) throw new PmsInvalid("The PMS returned incomplete stay dates."); var comments = row.TryGetProperty("comments",out var c) ? c : JsonSerializer.SerializeToElement(Array.Empty()); if (comments.ValueKind != JsonValueKind.Array) throw new PmsInvalid("OHIP comment format does not match the supported schema."); string guest="",room=""; if (row.TryGetProperty("reservationGuests",out var guests) && guests.ValueKind==JsonValueKind.Array) { var primary=guests.EnumerateArray().Where(g=>g.TryGetProperty("primary",out var flag)&&flag.ValueKind==JsonValueKind.True).ToArray(); if(primary.Length==1 && primary[0].TryGetProperty("profileInfo",out var info) && info.TryGetProperty("profile",out var profile) && profile.TryGetProperty("customer",out var customer) && customer.TryGetProperty("personName",out var names) && names.ValueKind==JsonValueKind.Array) {var name=names.EnumerateArray().FirstOrDefault(n=>Text(n,"nameType")=="Primary");if(name.ValueKind!=JsonValueKind.Undefined)guest=(Text(name,"givenName")+" "+Text(name,"surname")).Trim();} } if(row.TryGetProperty("roomStay",out var stay)&&stay.TryGetProperty("roomRates",out var rates)&&rates.ValueKind==JsonValueKind.Array)room=string.Join(", ",rates.EnumerateArray().Select(r=>Text(r,"roomType")).Where(r=>r.Length>0).Distinct()); var relevant = new JsonObject(); foreach(var key in new[]{"reservationIdList","hotelId","roomStay","comments","reservationStatus","lastModifyDateTime","reservationGuests"}) if(row.TryGetProperty(key,out var field)) relevant[key]=JsonNode.Parse(field.GetRawText()); return new PmsSnapshot { HotelId=hotel,ReservationId=id,Confirmation=confirmation,GuestName=guest,Arrival=arrival,Departure=departure,Status=Text(row,"reservationStatus"),RoomType=room,Total=(Text(row,"roomStay","total","amountAfterTax")+" "+Text(row,"roomStay","total","currencyCode")).Trim(),CommentsJson=comments.GetRawText(),ConnectionRevision=p.Revision,Fingerprint=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Canonical(relevant)))) }; } static string Canonical(JsonNode? n) => n is JsonObject obj ? "{"+string.Join(",",obj.OrderBy(x=>x.Key,StringComparer.Ordinal).Select(x=>JsonSerializer.Serialize(x.Key)+":"+Canonical(x.Value)))+"}" : n is JsonArray arr ? "["+string.Join(",",arr.Select(Canonical))+"]" : n?.ToJsonString()??"null"; public static string Payload(PmsChange change, OhipProfile profile) { var reservation=new JsonObject { ["hotelId"]=profile.HotelCode,["reservationIdList"]=JsonSerializer.SerializeToNode(new[]{new{id=change.ReservationId,type="Reservation"}}) }; if(change.Kind=="StayDates")reservation["roomStay"]=new JsonObject{["arrivalDate"]=change.Arrival,["departureDate"]=change.Departure}; else if(change.Kind=="AddNote") { var comments=JsonNode.Parse(change.Before.CommentsJson)!.AsArray(); if(comments.Count>=3999)throw new PmsInvalid("The reservation has too many notes to update safely."); comments.Add(new JsonObject { ["comment"]=new JsonObject { ["text"]=new JsonObject{["value"]=change.Note},["commentTitle"]="GuestOps "+change.Id,["type"]=profile.NoteType,["notificationLocation"]=profile.NoteLocation,["internal"]=true } }); reservation["comments"]=comments; } else throw new PmsInvalid("Unsupported PMS operation."); return new JsonObject{["reservations"]=new JsonArray(reservation)}.ToJsonString(); } public async Task Prepare(PmsChange change,OhipProfile profile,CancellationToken ct) { var request=await Request(change.HotelId,profile,HttpMethod.Put,Route(profile)+"/"+Segment(change.ReservationId),ct); request.Headers.Add("X-Request-Id",change.Id); request.Content=new StringContent(Payload(change,profile),Encoding.UTF8,"application/json");return request; } public async Task Write(HttpRequestMessage request,CancellationToken ct) { // No retry or redirect handler: all failures after entry are uncertain writes. using var response=await http.SendAsync(request,ct); response.EnsureSuccessStatusCode(); using var json=JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct)); if(json.RootElement.TryGetProperty("errors",out var errors)&&errors.ValueKind!=JsonValueKind.Null)throw new PmsInvalid("OHIP reported an update error."); if(json.RootElement.TryGetProperty("warnings",out var warnings)&&warnings.ValueKind==JsonValueKind.Array&&warnings.GetArrayLength()>0)throw new PmsInvalid("OHIP returned warnings requiring review."); } public static bool Matches(PmsChange change,PmsSnapshot after) { if(after.ReservationId!=change.ReservationId||after.HotelId!=change.HotelId)return false; if(change.Kind=="StayDates")return after.Arrival==change.Arrival&&after.Departure==change.Departure; using var json=JsonDocument.Parse(after.CommentsJson); return change.Kind=="AddNote" && json.RootElement.EnumerateArray().Count(n=>Text(n,"comment","commentTitle")=="GuestOps "+change.Id&&Text(n,"comment","text","value")==change.Note)==1; } }