Add reviewed OHIP reservation updates and durable reconciliation
This commit is contained in:
@@ -17,6 +17,8 @@ public static class Demo
|
||||
foreach (var k in new[] { ("Parking", "Complimentary parking is available in our courtyard, subject to availability. Spaces cannot be reserved.", "parking, car"), ("Check-in and luggage", "Check-in is from 3pm. Guests may leave their luggage with reception before check-in.", "check-in, luggage"), ("Breakfast", "Breakfast is served from 7am to 10am. Please ask our team about dietary requirements.", "breakfast") })
|
||||
await store.Insert(new KnowledgeEntry { HotelId = hotel.Id, Title = k.Item1, Category = "Your stay", Answer = k.Item2, Keywords = k.Item3, Approved = true });
|
||||
await store.Insert(new Activity { HotelId = hotel.Id, UserName = "GuestOps", Action = "Opened an isolated preview workspace" });
|
||||
var sample = new PmsSnapshot { HotelId=hotel.Id,ReservationId="sample-reservation",Confirmation="WH-2481",GuestName="Oliver Brooks",Arrival=DateTime.UtcNow.AddDays(10).ToString("yyyy-MM-dd"),Departure=DateTime.UtcNow.AddDays(12).ToString("yyyy-MM-dd"),RoomType="Garden King",Status="Reserved",Total="320 GBP" };
|
||||
await store.Insert(new PmsChange { HotelId=hotel.Id,ReservationId=sample.ReservationId,Before=sample,Kind="StayDates",Arrival=DateTime.UtcNow.AddDays(17).ToString("yyyy-MM-dd"),Departure=DateTime.UtcNow.AddDays(19).ToString("yyyy-MM-dd"),ProposedBy=user.Id,Detail="Sample proposal for interface review only. No PMS connection or update is available in this workspace." });
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ public abstract class TenantDocument : ITenantDocument
|
||||
}
|
||||
public class Hotel : TenantDocument
|
||||
{
|
||||
public bool PmsUpdatesEnabled { get; set; }
|
||||
public bool AiDraftsEnabled { get; set; }
|
||||
public bool StaffSendingEnabled { get; set; }
|
||||
public string Name { get; set; } = "";
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
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<string, (string Token, DateTime Until)> cache = new();
|
||||
readonly SemaphoreSlim gate = new(1,1);
|
||||
public async Task<string> 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<string,string> { ["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<HttpRequestMessage> 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<JsonElement> 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<PmsSnapshot> 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<PmsSnapshot> 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<object>());
|
||||
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<HttpRequestMessage> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.Security.Claims;
|
||||
namespace GuestOps.Web;
|
||||
|
||||
public static class PmsEndpoints
|
||||
{
|
||||
public static void Map(RouteGroupBuilder api,bool preview)
|
||||
{
|
||||
var group=api.MapGroup("/pms").RequireRateLimiting("pms");
|
||||
group.MapGet("/status",(HttpContext c,IConfiguration config)=>
|
||||
{
|
||||
var profile=preview?null:OhipProfile.Read(config,Session.Hotel(c));
|
||||
return Results.Ok(new{configured=profile!=null,writesConfigured=profile?.WritesEnabled==true,hotelCode=profile?.HotelCode??"",preview});
|
||||
});
|
||||
group.MapPost("/lookup",async(PmsLookupInput input,HttpContext c,PmsWork work)=>
|
||||
{
|
||||
if(preview)return Results.BadRequest(new{error="Real PMS connections are unavailable in preview."});
|
||||
var snapshot=await work.Lookup(Session.Hotel(c),input.Confirmation,c.RequestAborted);return Results.Ok(snapshot.View());
|
||||
});
|
||||
group.MapGet("/changes",async(HttpContext c,IStore store)=>Results.Ok((await store.List<PmsChange>(Session.Hotel(c))).OrderByDescending(x=>x.UpdatedAt).Select(x=>x.View())));
|
||||
group.MapPost("/changes",async(PmsProposeInput input,HttpContext c,PmsWork work,IStore store)=>
|
||||
{
|
||||
var snapshot=await store.Get<PmsSnapshot>(Session.Hotel(c),input.SnapshotId);if(snapshot==null)return Results.NotFound();
|
||||
if(preview)return Results.BadRequest();
|
||||
var change=await work.Propose(Session.Hotel(c),c.User.FindFirstValue(ClaimTypes.NameIdentifier)!,snapshot,input);
|
||||
await Session.Audit(store,c,"Prepared a PMS change for review");return Results.Ok(change.View());
|
||||
}).RequireAuthorization("Owner");
|
||||
group.MapPost("/changes/{id}/apply",async(string id,PmsApproveInput input,HttpContext c,PmsWork work,IStore store)=>
|
||||
{
|
||||
var change=await store.Get<PmsChange>(Session.Hotel(c),id);if(change==null)return Results.NotFound();if(preview)return Results.BadRequest();
|
||||
var result=await work.Apply(change,input.Version,c.User.FindFirstValue(ClaimTypes.NameIdentifier)!,input.AvailabilityAndPriceChecked,c.RequestAborted);
|
||||
await Session.Audit(store,c,"PMS change result: "+result.State);return Results.Ok(result.View());
|
||||
}).RequireAuthorization("Owner");
|
||||
group.MapPost("/changes/{id}/verify",async(string id,VersionInput input,HttpContext c,PmsWork work,IStore store)=>
|
||||
{
|
||||
var change=await store.Get<PmsChange>(Session.Hotel(c),id);if(change==null)return Results.NotFound();if(preview)return Results.BadRequest();
|
||||
var result=await work.Verify(change,input.Version,c.RequestAborted);await Session.Audit(store,c,"Verified PMS state: "+result.State);return Results.Ok(result.View());
|
||||
}).RequireAuthorization("Owner");
|
||||
group.MapPost("/changes/{id}/cancel",async(string id,VersionInput input,HttpContext c,PmsWork work,IStore store)=>
|
||||
{
|
||||
var change=await store.Get<PmsChange>(Session.Hotel(c),id);if(change==null)return Results.NotFound();if(preview)return Results.BadRequest();
|
||||
var result=await work.Cancel(change,input.Version);await Session.Audit(store,c,"Cancelled an unapplied PMS proposal");return Results.Ok(result.View());
|
||||
}).RequireAuthorization("Owner");
|
||||
group.MapPut("/controls",async(PmsControlsInput input,HttpContext c,IStore store,IConfiguration config)=>
|
||||
{
|
||||
if(input.Enabled&&(preview||OhipProfile.Read(config,Session.Hotel(c))?.WritesEnabled!=true))return Results.BadRequest(new{error="Server-side PMS writes must be enabled after sandbox acceptance first."});
|
||||
var hotel=await store.Get<Hotel>(Session.Hotel(c),Session.Hotel(c));if(hotel==null)return Results.NotFound();hotel.PmsUpdatesEnabled=input.Enabled;hotel.Version=input.Version+1;
|
||||
if(!await store.Replace(hotel.HotelId,hotel.Id,input.Version,hotel))return Input.Conflict();
|
||||
await Session.Audit(store,c,"Updated PMS write controls");return Results.Ok(hotel);
|
||||
}).RequireAuthorization("Owner");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
namespace GuestOps.Web;
|
||||
|
||||
public sealed class PmsSnapshot : TenantDocument
|
||||
{
|
||||
public string ReservationId { get; set; } = "";
|
||||
public string Confirmation { get; set; } = "";
|
||||
public string GuestName { get; set; } = "";
|
||||
public string Arrival { get; set; } = "";
|
||||
public string Departure { get; set; } = "";
|
||||
public string Status { get; set; } = "";
|
||||
public string RoomType { get; set; } = "";
|
||||
public string Total { get; set; } = "";
|
||||
public string CommentsJson { get; set; } = "[]";
|
||||
public string Fingerprint { get; set; } = "";
|
||||
public string ConnectionRevision { get; set; } = "";
|
||||
public DateTime FetchedAt { get; set; } = DateTime.UtcNow;
|
||||
public object View() => new { Id, ReservationId, Confirmation, GuestName, Arrival, Departure, Status, RoomType, Total, FetchedAt };
|
||||
}
|
||||
public sealed class PmsChange : TenantDocument
|
||||
{
|
||||
public string ReservationId { get; set; } = "";
|
||||
public PmsSnapshot Before { get; set; } = new();
|
||||
public PmsSnapshot? After { get; set; }
|
||||
public string Kind { get; set; } = "";
|
||||
public string Arrival { get; set; } = "";
|
||||
public string Departure { get; set; } = "";
|
||||
public string Note { get; set; } = "";
|
||||
public string State { get; set; } = "Review";
|
||||
public string Detail { get; set; } = "Review the reservation and proposed change before applying.";
|
||||
public string ProposedBy { get; set; } = "";
|
||||
public string ApprovedBy { get; set; } = "";
|
||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||
public DateTime ExpiresAt { get; set; } = DateTime.UtcNow.AddMinutes(10);
|
||||
public long Version { get; set; }
|
||||
public static bool Active(string state) => state is "Review" or "Applying" or "NeedsReview";
|
||||
public object View() => new { Id, ReservationId, Kind, Arrival, Departure, Note, State, Detail, ProposedBy, ApprovedBy, UpdatedAt, ExpiresAt, Version, before = Before.View(), after = After?.View() };
|
||||
}
|
||||
public sealed record PmsLookupInput(string Confirmation);
|
||||
public sealed record PmsProposeInput(string SnapshotId, string Kind, string Arrival, string Departure, string Note);
|
||||
public sealed record PmsApproveInput(long Version, bool AvailabilityAndPriceChecked);
|
||||
public sealed record PmsControlsInput(long Version, bool Enabled);
|
||||
public sealed class PmsConflict(string message) : Exception(message);
|
||||
public sealed class PmsInvalid(string message) : Exception(message);
|
||||
|
||||
public sealed class OhipProfile
|
||||
{
|
||||
public string BaseUrl { get; set; } = "";
|
||||
public string HotelCode { get; set; } = "";
|
||||
public string ClientId { get; set; } = "";
|
||||
public string ClientSecret { get; set; } = "";
|
||||
public string AppKey { get; set; } = "";
|
||||
public string EnterpriseId { get; set; } = "";
|
||||
public string Scope { get; set; } = "urn:opc:hgbu:ws:__myscopes__";
|
||||
public bool WritesEnabled { get; set; }
|
||||
public string NoteType { get; set; } = "RESERVATION";
|
||||
public string NoteLocation { get; set; } = "GEN";
|
||||
// Write enablement is a stop control, not a credential identity: verification
|
||||
// must remain possible after an administrator turns writes off.
|
||||
public string Revision => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { BaseUrl, HotelCode, ClientId, ClientSecret, AppKey, EnterpriseId, Scope, NoteType, NoteLocation }))));
|
||||
public static OhipProfile? Read(IConfiguration config, string hotel)
|
||||
{
|
||||
if (!System.Text.RegularExpressions.Regex.IsMatch(hotel, "^[a-f0-9]{32}$")) return null;
|
||||
var section = config.GetSection("Pms:Hotels:" + hotel);
|
||||
if (!section.Exists()) return null;
|
||||
var profile = section.Get<OhipProfile>();
|
||||
if (profile == null || !Uri.TryCreate(profile.BaseUrl, UriKind.Absolute, out var uri) || uri.Scheme != "https" || uri.Port != 443 || uri.AbsolutePath != "/" || uri.UserInfo.Length > 0 || uri.Query.Length > 0 || uri.Fragment.Length > 0 || uri.IsLoopback) throw new PmsInvalid("The administrator must configure a valid HTTPS OHIP origin.");
|
||||
foreach (var value in new[] { profile.HotelCode, profile.ClientId, profile.ClientSecret, profile.AppKey, profile.Scope, profile.NoteType, profile.NoteLocation })
|
||||
if (string.IsNullOrWhiteSpace(value) || value.Length > 4000 || value.IndexOfAny(['\r','\n']) >= 0) throw new PmsInvalid("The administrator must complete the OHIP connection settings.");
|
||||
if (profile.HotelCode.Length > 20 || profile.NoteType.Length > 20 || profile.NoteLocation.Length > 20 || profile.ClientId.Contains(':')) throw new PmsInvalid("Invalid OHIP identifiers.");
|
||||
return profile;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using System.Globalization;
|
||||
namespace GuestOps.Web;
|
||||
|
||||
public sealed class PmsWork(IStore store,OhipClient ohip,IConfiguration config)
|
||||
{
|
||||
public OhipProfile Profile(string hotel)=>OhipProfile.Read(config,hotel)??throw new PmsInvalid("Your administrator has not configured OHIP for this hotel.");
|
||||
async Task WritesAllowed(string hotel,OhipProfile profile)
|
||||
{
|
||||
if(!profile.WritesEnabled||(await store.Get<Hotel>(hotel,hotel))?.PmsUpdatesEnabled!=true)throw new PmsInvalid("PMS updates are disabled. Enable them only after sandbox acceptance.");
|
||||
}
|
||||
public async Task<PmsSnapshot> Lookup(string hotel,string confirmation,CancellationToken ct)
|
||||
{
|
||||
var snapshot=await ohip.Lookup(hotel,Profile(hotel),confirmation,ct);await store.Insert(snapshot);return snapshot;
|
||||
}
|
||||
public async Task<PmsChange> Propose(string hotel,string user,PmsSnapshot snapshot,PmsProposeInput input)
|
||||
{
|
||||
var profile=Profile(hotel);
|
||||
if(snapshot.HotelId!=hotel||snapshot.ConnectionRevision!=profile.Revision||snapshot.FetchedAt<DateTime.UtcNow.AddMinutes(-10))throw new PmsConflict("Look up the reservation again before preparing a change.");
|
||||
if(input.Kind is not ("StayDates" or "AddNote"))throw new PmsInvalid("Choose a supported PMS action.");
|
||||
var change=new PmsChange{HotelId=hotel,ReservationId=snapshot.ReservationId,Before=snapshot,Kind=input.Kind,ProposedBy=user};
|
||||
if(input.Kind=="StayDates")
|
||||
{
|
||||
if(snapshot.Status!="Reserved")throw new PmsInvalid("Only reserved stays can have dates changed here. Handle other statuses in the PMS.");
|
||||
if(!DateOnly.TryParseExact(input.Arrival,"yyyy-MM-dd",CultureInfo.InvariantCulture,DateTimeStyles.None,out var arrival)||!DateOnly.TryParseExact(input.Departure,"yyyy-MM-dd",CultureInfo.InvariantCulture,DateTimeStyles.None,out var departure)||departure<=arrival||departure.DayNumber-arrival.DayNumber>365)throw new PmsInvalid("Enter valid arrival and departure dates for a stay of at most 365 nights.");
|
||||
if(input.Arrival==snapshot.Arrival&&input.Departure==snapshot.Departure)throw new PmsInvalid("The proposed dates are unchanged.");
|
||||
change.Arrival=input.Arrival;change.Departure=input.Departure;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(!Input.Text(input.Note,1,2000))throw new PmsInvalid("Enter a reservation note of at most 2,000 characters.");
|
||||
change.Note=input.Note.Trim();
|
||||
}
|
||||
_=OhipClient.Payload(change,profile);
|
||||
if(!await store.TryInsertPmsChange(change))throw new PmsConflict("A change is already being reviewed or needs reconciliation for this reservation. Resolve it in the change history first.");
|
||||
return change;
|
||||
}
|
||||
async Task Save(PmsChange change,string state,string detail)
|
||||
{
|
||||
var version=change.Version;change.Version++;change.State=state;change.Detail=detail;change.UpdatedAt=DateTime.UtcNow;
|
||||
if(!await store.Replace(change.HotelId,change.Id,version,change))throw new PmsConflict("This change was updated elsewhere. Refresh its status.");
|
||||
}
|
||||
public async Task<PmsChange> Apply(PmsChange change,long version,string approver,bool priceChecked,CancellationToken requestToken)
|
||||
{
|
||||
if(change.State!="Review"||change.Version!=version)throw new PmsConflict("Only the current reviewed proposal can be applied once.");
|
||||
if(change.ExpiresAt<DateTime.UtcNow)throw new PmsConflict("This proposal expired. Cancel it and look up the reservation again.");
|
||||
if(change.Kind=="StayDates"&&!priceChecked)throw new PmsInvalid("Check availability, rate consequences and guest agreement in the PMS before approving these dates.");
|
||||
var profile=Profile(change.HotelId);await WritesAllowed(change.HotelId,profile);
|
||||
if(profile.Revision!=change.Before.ConnectionRevision)throw new PmsConflict("OHIP configuration changed. Cancel this proposal and look up the reservation again.");
|
||||
change.ApprovedBy=approver;
|
||||
await Save(change,"Applying","Checking the current PMS reservation before submitting the approved change.");
|
||||
using var deadline=CancellationTokenSource.CreateLinkedTokenSource(requestToken);deadline.CancelAfter(TimeSpan.FromSeconds(90));
|
||||
bool submitted=false;
|
||||
try
|
||||
{
|
||||
var current=await ohip.Fetch(change.HotelId,profile,change.ReservationId,change.Before.Confirmation,deadline.Token);
|
||||
if(current.Fingerprint!=change.Before.Fingerprint){await Save(change,"NotApplied","The PMS reservation changed after lookup. No update was sent. Prepare a fresh proposal.");return change;}
|
||||
using var request=await ohip.Prepare(change,profile,deadline.Token);
|
||||
await WritesAllowed(change.HotelId,profile);deadline.Token.ThrowIfCancellationRequested();
|
||||
submitted=true;await ohip.Write(request,deadline.Token);
|
||||
var after=await ohip.Fetch(change.HotelId,profile,change.ReservationId,change.Before.Confirmation,deadline.Token);change.After=after;
|
||||
if(!OhipClient.Matches(change,after))throw new PmsConflict("The PMS response did not confirm the intended state.");
|
||||
await Save(change,"Applied","The requested state was confirmed by reading the reservation back from OHIP. Check rate consequences in the PMS.");
|
||||
}
|
||||
catch(Exception) { await Save(change,submitted?"NeedsReview":"NotApplied",submitted?"The PMS update outcome is uncertain. Verify current PMS state; this operation will not be replayed.":"The pre-update check failed. No PMS update was submitted. Check the connection and prepare a new proposal."); }
|
||||
return change;
|
||||
}
|
||||
public async Task<PmsChange> Verify(PmsChange change,long version,CancellationToken ct)
|
||||
{
|
||||
if(change.Version!=version || !(change.State=="NeedsReview" || change.State=="Applying"&&change.UpdatedAt<DateTime.UtcNow.AddMinutes(-5)))throw new PmsConflict("Only an uncertain or interrupted update can be verified.");
|
||||
var profile=Profile(change.HotelId);
|
||||
if(profile.Revision!=change.Before.ConnectionRevision)throw new PmsConflict("The connection changed. Restore the original hotel binding before reconciliation.");
|
||||
var after=await ohip.Fetch(change.HotelId,profile,change.ReservationId,change.Before.Confirmation,ct);change.After=after;
|
||||
await Save(change,OhipClient.Matches(change,after)?"Applied":"NeedsReview",OhipClient.Matches(change,after)?"The intended state is now confirmed in OHIP. This observation does not identify who made the change.":"The intended state is not confirmed. Keep this update on hold and reconcile manually in the PMS; no retry was queued.");return change;
|
||||
}
|
||||
public async Task<PmsChange> Cancel(PmsChange change,long version)
|
||||
{
|
||||
if(change.State!="Review"||change.Version!=version)throw new PmsConflict("Only a proposal that has not started can be cancelled.");
|
||||
await Save(change,"Cancelled","The proposal was cancelled before any PMS update.");return change;
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ using System.Net;
|
||||
|
||||
var bootstrap = args.Contains("--bootstrap");
|
||||
var builder = WebApplication.CreateBuilder(args.Where(arg => arg != "--bootstrap").ToArray());
|
||||
if (builder.Configuration["Pms:ConfigFile"] is { Length: > 0 } pmsConfigFile) builder.Configuration.AddJsonFile(pmsConfigFile,optional:false,reloadOnChange:false);
|
||||
builder.Logging.ClearProviders(); builder.Logging.AddConsole();
|
||||
builder.Logging.AddFilter("Microsoft.AspNetCore.Hosting.Diagnostics", LogLevel.Warning);
|
||||
builder.Logging.AddFilter("System.Net.Http.HttpClient", LogLevel.Warning);
|
||||
@@ -27,6 +28,9 @@ builder.Services.AddSingleton<IStore>(s => preview ? new PreviewStore() : new Mo
|
||||
builder.Services.AddSingleton<IPasswordHasher<StaffUser>, PasswordHasher<StaffUser>>();
|
||||
builder.Services.AddHttpClient<GoogleMailbox>(c => c.Timeout = TimeSpan.FromSeconds(25)).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
builder.Services.AddHttpClient<AiDrafts>(c => c.Timeout = TimeSpan.FromSeconds(60)).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
builder.Services.AddSingleton<OhipTokens>();
|
||||
builder.Services.AddHttpClient<OhipClient>(c => c.Timeout = TimeSpan.FromSeconds(25)).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
builder.Services.AddTransient<PmsWork>();
|
||||
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
|
||||
{
|
||||
o.Cookie.Name = "guestops.session"; o.Cookie.HttpOnly = true; o.Cookie.SameSite = SameSiteMode.Lax;
|
||||
@@ -55,6 +59,7 @@ builder.Services.AddAntiforgery(o => { o.HeaderName = "X-CSRF-TOKEN"; o.Cookie.N
|
||||
builder.Services.AddRateLimiter(o =>
|
||||
{
|
||||
o.RejectionStatusCode = 429;
|
||||
o.AddPolicy("pms", context => RateLimitPartition.GetFixedWindowLimiter(context.User.FindFirstValue("hotel") ?? "anonymous", _ => new() { PermitLimit = 30, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }));
|
||||
o.AddPolicy("ai", context => RateLimitPartition.GetFixedWindowLimiter(context.User.FindFirstValue("hotel") ?? "anonymous", _ => new() { PermitLimit = 6, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }));
|
||||
o.AddPolicy("login", context => RateLimitPartition.GetFixedWindowLimiter(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new() { PermitLimit = 10, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }));
|
||||
});
|
||||
@@ -82,6 +87,8 @@ app.Use(async (ctx, next) =>
|
||||
ctx.Response.Headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'";
|
||||
if (ctx.Request.Path.StartsWithSegments("/api")) ctx.Response.Headers.CacheControl = "no-store";
|
||||
try { await next(); }
|
||||
catch (PmsInvalid ex) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
|
||||
catch (PmsConflict ex) { ctx.Response.StatusCode = 409; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
|
||||
catch (AntiforgeryValidationException) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = "Your session needs refreshing. Reload the page and try again." }); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -116,6 +123,7 @@ app.MapPost("/api/auth/login", async (LoginInput input, HttpContext c, IPassword
|
||||
app.MapPost("/api/auth/logout", async (HttpContext c, CancellationToken _) => { await c.SignOutAsync(); return Results.Ok(); }).RequireAuthorization();
|
||||
if (preview) app.MapPost("/api/preview/start", async (HttpContext c, CancellationToken _) => { var user = await Demo.Seed(store); await Session.SignIn(c, user); return Results.Ok(); }).RequireRateLimiting("login");
|
||||
var api = app.MapGroup("/api").RequireAuthorization();
|
||||
PmsEndpoints.Map(api,preview);
|
||||
api.MapGet("/hotel", async (HttpContext c, CancellationToken _) => Results.Ok(await store.Get<Hotel>(Session.Hotel(c), Session.Hotel(c))));
|
||||
api.MapPut("/hotel", async (SettingsInput input, HttpContext c) =>
|
||||
{
|
||||
@@ -261,4 +269,3 @@ namespace GuestOps.Web
|
||||
public static IResult Conflict() => Results.Conflict(new { error = "Someone changed this record. Reload it before saving again." });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -62,4 +62,3 @@ public sealed class ReplyDelivery(IStore store, GoogleMailbox google)
|
||||
catch { await Save("NeedsReview", "Gmail's delivery result is uncertain. Verify delivery; this reply will not be automatically sent again."); }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ public interface IStore
|
||||
Task ReleaseLease(string id, string owner);
|
||||
Task Import(Conversation message);
|
||||
Task<List<Conversation>> Deliveries();
|
||||
Task<bool> TryInsertPmsChange(PmsChange change);
|
||||
}
|
||||
public sealed class MongoStore : IStore
|
||||
{
|
||||
@@ -41,6 +42,9 @@ public sealed class MongoStore : IStore
|
||||
}
|
||||
public async Task Initialize()
|
||||
{
|
||||
await Collection<PmsChange>().Indexes.CreateOneAsync(new CreateIndexModel<PmsChange>(Builders<PmsChange>.IndexKeys.Ascending(x=>x.HotelId).Ascending(x=>x.ReservationId),new CreateIndexOptions<PmsChange>{Unique=true,PartialFilterExpression=Builders<PmsChange>.Filter.In(x=>x.State,new[]{"Review","Applying","NeedsReview"})}));
|
||||
await Collection<PmsChange>().Indexes.CreateOneAsync(new CreateIndexModel<PmsChange>(Builders<PmsChange>.IndexKeys.Ascending(x=>x.HotelId).Descending(x=>x.UpdatedAt)));
|
||||
await Collection<PmsSnapshot>().Indexes.CreateOneAsync(new CreateIndexModel<PmsSnapshot>(Builders<PmsSnapshot>.IndexKeys.Ascending(x=>x.FetchedAt),new(){ExpireAfter=TimeSpan.FromDays(1)}));
|
||||
await Collection<StaffUser>().Indexes.CreateOneAsync(new CreateIndexModel<StaffUser>(Builders<StaffUser>.IndexKeys.Ascending(x => x.Email), new() { Unique = true }));
|
||||
await Collection<Conversation>().Indexes.CreateOneAsync(new CreateIndexModel<Conversation>(Builders<Conversation>.IndexKeys.Ascending(x => x.HotelId).Ascending(x => x.MailboxId).Ascending(x => x.ProviderMessageId), new() { Unique = true }));
|
||||
await Collection<Conversation>().Indexes.CreateOneAsync(new CreateIndexModel<Conversation>(Builders<Conversation>.IndexKeys.Ascending(x => x.HotelId).Descending(x => x.ReceivedAt)));
|
||||
@@ -53,6 +57,7 @@ public sealed class MongoStore : IStore
|
||||
var query = Collection<T>().Find(Scope<T>(hotel));
|
||||
if (typeof(T) == typeof(Conversation)) query = query.Sort(Builders<T>.Sort.Descending("ReceivedAt"));
|
||||
if (typeof(T) == typeof(Activity)) query = query.Sort(Builders<T>.Sort.Descending("At"));
|
||||
if (typeof(T) == typeof(PmsChange)) query = query.Sort(Builders<T>.Sort.Descending("UpdatedAt"));
|
||||
return query.Limit(500).ToListAsync();
|
||||
}
|
||||
public async Task<T?> Get<T>(string hotel, string id) where T : TenantDocument => await Collection<T>().Find(Scope<T>(hotel) & Builders<T>.Filter.Eq(x => x.Id, id)).FirstOrDefaultAsync();
|
||||
@@ -93,11 +98,24 @@ public sealed class MongoStore : IStore
|
||||
try { await Insert(message); }
|
||||
catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey) { /* already durable */ }
|
||||
}
|
||||
public async Task<bool> TryInsertPmsChange(PmsChange change)
|
||||
{
|
||||
try { await Insert(change);return true; }
|
||||
catch(MongoWriteException ex) when(ex.WriteError.Category==ServerErrorCategory.DuplicateKey){return false;}
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit Development-only preview store. Production never falls back to this.
|
||||
public sealed class PreviewStore : IStore
|
||||
{
|
||||
public Task<bool> TryInsertPmsChange(PmsChange change)
|
||||
{
|
||||
lock(gate)
|
||||
{
|
||||
if(rows.Where(x=>x.Key.StartsWith("PmsChange:")).Select(x=>Clone<PmsChange>(x.Value)).Any(x=>x.HotelId==change.HotelId&&x.ReservationId==change.ReservationId&&PmsChange.Active(x.State)))return Task.FromResult(false);
|
||||
return Task.FromResult(rows.TryAdd(Key<PmsChange>(change.Id),Json(change)));
|
||||
}
|
||||
}
|
||||
public Task<List<Conversation>> Deliveries() => Task.FromResult(rows.Where(x => x.Key.StartsWith("Conversation:")).Select(x => Clone<Conversation>(x.Value)).Where(x => x.Delivery?.State is "Pending" or "Sending").ToList());
|
||||
private readonly ConcurrentDictionary<string, string> rows = new();
|
||||
private readonly object gate = new();
|
||||
|
||||
@@ -69,4 +69,3 @@ sealed class DeliveryWorker(IStore store, IServiceScopeFactory factory, ILogger<
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user