Files
GuestOps/src/GuestOps.Api/PmsWork.cs
T

81 lines
6.8 KiB
C#

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;
}
}