Add reviewed NMI hosted invoices and read-only payment reconciliation

This commit is contained in:
wolf-demon
2026-09-15 09:31:05 +01:00
parent 5bd71175c0
commit ad57a8b1bd
20 changed files with 411 additions and 12 deletions
+1
View File
@@ -19,6 +19,7 @@ public static class Demo
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." });
await store.Insert(new PaymentRequest {HotelId=hotel.Id,Reference="WH-2481-DEPOSIT",Email="guest@example.invalid",Description="Deposit for Oliver Brooks · WH-2481",Amount=80,Currency="GBP",ProposedBy=user.Id,Detail="Sample proposal only. No invoice or email can be created in preview."});
return user;
}
}
+1
View File
@@ -9,6 +9,7 @@ public abstract class TenantDocument : ITenantDocument
}
public class Hotel : TenantDocument
{
public bool PaymentsEnabled { get; set; }
public bool PmsUpdatesEnabled { get; set; }
public bool AiDraftsEnabled { get; set; }
public bool StaffSendingEnabled { get; set; }
+32
View File
@@ -0,0 +1,32 @@
using System.Security.Claims;
namespace GuestOps.Web;
public static class PaymentEndpoints
{
public static void Map(RouteGroupBuilder api,bool preview)
{
var group=api.MapGroup("/payments").RequireRateLimiting("pms");
group.MapGet("/status",(HttpContext c,IConfiguration config)=>{var p=preview?null:NmiProfile.Read(config,Session.Hotel(c));return Results.Ok(new{configured=p!=null,createsConfigured=p?.CreatesEnabled==true,sandbox=p?.BaseUrl=="https://sandbox.nmi.com",preview});});
group.MapGet("/requests",async(HttpContext c,IStore store)=>Results.Ok((await store.List<PaymentRequest>(Session.Hotel(c))).OrderByDescending(p=>p.UpdatedAt).Select(p=>p.View())));
group.MapPost("/requests",async(PaymentInput input,HttpContext c,PaymentWork work,IStore store)=>{
if(preview)return Results.BadRequest(new{error="Real payment creation is disabled in preview."});
var p=await work.Propose(Session.Hotel(c),c.User.FindFirstValue(ClaimTypes.NameIdentifier)!,input);await Session.Audit(store,c,"Prepared payment request for review");return Results.Ok(p.View());
}).RequireAuthorization("Owner");
group.MapPost("/requests/{id}/create",async(string id,PaymentApproval input,HttpContext c,PaymentWork work,IStore store)=>{
var p=await store.Get<PaymentRequest>(Session.Hotel(c),id);if(p==null)return Results.NotFound();if(preview)return Results.BadRequest();
var result=await work.Create(p,input.Version,c.User.FindFirstValue(ClaimTypes.NameIdentifier)!,input.EmailAndAmountApproved,c.RequestAborted);await Session.Audit(store,c,"Payment creation result: "+result.State);return Results.Ok(result.View());
}).RequireAuthorization("Owner");
group.MapPost("/requests/{id}/check",async(string id,VersionInput input,HttpContext c,PaymentWork work,IStore store)=>{
var p=await store.Get<PaymentRequest>(Session.Hotel(c),id);if(p==null)return Results.NotFound();if(preview)return Results.BadRequest();
var result=await work.Check(p,input.Version,c.RequestAborted);await Session.Audit(store,c,"Checked payment invoice: "+result.State);return Results.Ok(result.View());
}).RequireAuthorization("Owner");
group.MapPost("/requests/{id}/cancel",async(string id,VersionInput input,HttpContext c,PaymentWork work,IStore store)=>{
var p=await store.Get<PaymentRequest>(Session.Hotel(c),id);if(p==null)return Results.NotFound();if(preview)return Results.BadRequest();
var result=await work.Cancel(p,input.Version);await Session.Audit(store,c,"Cancelled unsubmitted payment proposal");return Results.Ok(result.View());
}).RequireAuthorization("Owner");
group.MapPut("/controls",async(PmsControlsInput input,HttpContext c,IStore store,IConfiguration config)=>{
if(input.Enabled&&(preview||NmiProfile.Read(config,Session.Hotel(c))?.CreatesEnabled!=true))return Results.BadRequest(new{error="Administrator payment enablement and sandbox acceptance are required first."});
var hotel=await store.Get<Hotel>(Session.Hotel(c),Session.Hotel(c));if(hotel==null)return Results.NotFound();hotel.PaymentsEnabled=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 payment creation control");return Results.Ok(hotel);
}).RequireAuthorization("Owner");
}
}
+147
View File
@@ -0,0 +1,147 @@
using System.Globalization;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace GuestOps.Web;
public sealed class PaymentRequest : TenantDocument
{
public string Reference { get; set; } = "";
public string Email { get; set; } = "";
public string Description { get; set; } = "";
public decimal Amount { get; set; }
public string Currency { get; set; } = "GBP";
public string State { get; set; } = "Review";
public string Detail { get; set; } = "Review amount, currency and recipient before creating the invoice.";
public string InvoiceId { get; set; } = "";
public string Binding { get; set; } = "";
public string Revision { get; set; } = "";
public string ProposedBy { get; set; } = "";
public string ApprovedBy { get; set; } = "";
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
public DateTime? CheckedAt { get; set; }
public DateTime ExpiresAt { get; set; } = DateTime.UtcNow.AddMinutes(15);
public long Version { get; set; }
public object View()=>new {Id,Reference,Email,Description,Amount,Currency,State,Detail,InvoiceId,ProposedBy,ApprovedBy,CreatedAt,UpdatedAt,CheckedAt,ExpiresAt,Version};
}
public sealed record PaymentInput(string Reference,string Email,string Description,decimal Amount,string Currency);
public sealed record PaymentApproval(long Version,bool EmailAndAmountApproved);
public sealed class PaymentInvalid(string message):Exception(message);
public sealed class PaymentConflict(string message):Exception(message);
public sealed class NmiProfile
{
public string BaseUrl {get;set;}="https://sandbox.nmi.com";
public string MerchantAccount {get;set;}="";
public string SecurityKey {get;set;}="";
public bool CreatesEnabled {get;set;}
public string Binding=>Hash(BaseUrl+"|"+MerchantAccount);
public string Revision=>Hash(Binding+"|"+SecurityKey);
static string Hash(string s)=>Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(s)));
public static NmiProfile? Read(IConfiguration config,string hotel)
{
if(!Regex.IsMatch(hotel,"^[a-f0-9]{32}$"))return null;
var section=config.GetSection("Payments:Hotels:"+hotel);if(!section.Exists())return null;
var p=section.Get<NmiProfile>()!;
if(p.BaseUrl is not ("https://sandbox.nmi.com" or "https://secure.nmi.com") || !Regex.IsMatch(p.MerchantAccount,"^[A-Za-z0-9_-]{1,100}$") || string.IsNullOrWhiteSpace(p.SecurityKey)||p.SecurityKey.Length>4000||p.SecurityKey.Any(char.IsControl))throw new PaymentInvalid("The administrator must complete a valid NMI merchant configuration.");
return p;
}
}
public sealed class NmiInvoices(HttpClient http)
{
public static string Text(JsonElement e,string name)=>e.ValueKind==JsonValueKind.Object&&e.TryGetProperty(name,out var v)&&v.ValueKind is JsonValueKind.String or JsonValueKind.Number?v.ToString():"";
public static string Id(JsonElement e){var id=Text(e,"id");if(!Regex.IsMatch(id,"^[1-9][0-9]{0,19}$"))throw new PaymentInvalid("NMI returned an invalid invoice identity.");return id;}
public static object Payload(PaymentRequest p)=>new {amount=p.Amount,currency=p.Currency,payment_terms="upon_receipt",payment_methods_allowed=new[]{"cc"},billing_address=new{email=p.Email},order_details=new{order_id=p.Id,order_description=p.Description}};
async Task<JsonElement> Send(NmiProfile profile,HttpMethod method,string path,object? body,CancellationToken ct)
{
using var request=new HttpRequestMessage(method,profile.BaseUrl+"/api/v5/"+path);
request.Headers.Add("Authorization",profile.SecurityKey);
request.Headers.Accept.ParseAdd("application/json");
if(body!=null){request.Content=new StringContent(JsonSerializer.Serialize(body),Encoding.UTF8);request.Content.Headers.ContentType=new("application/json");}
using var response=await http.SendAsync(request,ct);response.EnsureSuccessStatusCode();
using var json=JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct));return json.RootElement.Clone();
}
public Task<JsonElement> Create(NmiProfile profile,PaymentRequest p,CancellationToken ct)=>Send(profile,HttpMethod.Post,"invoices",Payload(p),ct);
public Task<JsonElement> Get(NmiProfile profile,string id,CancellationToken ct)
{
if(!Regex.IsMatch(id,"^[1-9][0-9]{0,19}$"))throw new PaymentInvalid("Invalid invoice ID.");
return Send(profile,HttpMethod.Get,"invoices/"+id,null,ct);
}
public async Task<JsonElement> Find(NmiProfile profile,PaymentRequest p,CancellationToken ct)
{
var matches=new List<JsonElement>();var cursor="";var seen=new HashSet<string>();
for(int page=0;page<10;page++)
{
var result=await Send(profile,HttpMethod.Get,"invoices?per_page=100&date_from="+p.CreatedAt.AddDays(-1).ToString("yyyy-MM-dd",CultureInfo.InvariantCulture)+(cursor.Length>0?"&cursor="+cursor:""),null,ct);
if(!result.TryGetProperty("invoices",out var rows)||rows.ValueKind!=JsonValueKind.Array)throw new PaymentInvalid("NMI invoice search could not be verified.");
foreach(var row in rows.EnumerateArray())if(row.TryGetProperty("order_details",out var order)&&Text(order,"order_id")==p.Id)matches.Add(row.Clone());
if(matches.Count>1)throw new PaymentConflict("More than one invoice matches. Reconcile in the NMI portal; do not create another.");
if(!result.TryGetProperty("next_cursor",out var next))throw new PaymentInvalid("NMI pagination is incomplete.");
if(next.ValueKind==JsonValueKind.Null){if(matches.Count!=1)throw new PaymentConflict("No invoice was confirmed. Keep this request on hold and check NMI; creation will not be repeated.");return matches[0];}
cursor=next.ToString();if(!Regex.IsMatch(cursor,"^[1-9][0-9]{0,19}$")||!seen.Add(cursor))throw new PaymentInvalid("NMI pagination could not be verified.");
}
throw new PaymentConflict("The invoice search exceeded its limit. Reconcile in the NMI portal.");
}
public static string Verify(PaymentRequest p,JsonElement e)
{
var id=Id(e);
if(Text(e,"object")!="invoice"||(p.InvoiceId.Length>0&&p.InvoiceId!=id)||!e.TryGetProperty("order_details",out var order)||Text(order,"order_id")!=p.Id||!e.TryGetProperty("billing_address",out var billing)||!string.Equals(Text(billing,"email"),p.Email,StringComparison.OrdinalIgnoreCase)||Text(e,"currency")!=p.Currency||!decimal.TryParse(Text(e,"amount"),NumberStyles.AllowDecimalPoint,CultureInfo.InvariantCulture,out var amount)||amount!=p.Amount)throw new PaymentConflict("Invoice identity, recipient, amount or currency does not match. Reconcile in NMI.");
return Text(e,"status") switch {"open"=>"Open","overdue"=>"Overdue","partially_paid"=>"Partial","paid"=>"Paid","closed"=>"Closed",_=>throw new PaymentConflict("NMI returned an unrecognised invoice status.")};
}
}
public sealed class PaymentWork(IStore store,NmiInvoices nmi,IConfiguration config)
{
NmiProfile Profile(string hotel)=>NmiProfile.Read(config,hotel)??throw new PaymentInvalid("Your administrator has not configured NMI for this hotel.");
public async Task<PaymentRequest> Propose(string hotel,string user,PaymentInput input)
{
var profile=Profile(hotel);
if(!Regex.IsMatch(input.Reference??"","^[A-Za-z0-9-]{1,80}$")||!Input.Text(input.Description,1,250)||input.Amount<=0||input.Amount>100000||decimal.Round(input.Amount,2)!=input.Amount||input.Currency is not ("GBP" or "EUR" or "USD"))throw new PaymentInvalid("Use a unique payment reference, a description, and an amount from 0.01 to 100,000 with two decimal places in GBP, EUR or USD.");
if(!MailAddress.TryCreate(input.Email,out var email)||email.Address!=input.Email||input.Email.Length>254||input.Email.Any(char.IsControl))throw new PaymentInvalid("Enter one plain customer email address.");
var p=new PaymentRequest{HotelId=hotel,Reference=input.Reference!.ToUpperInvariant(),Email=email.Address,Description=input.Description.Trim(),Amount=input.Amount,Currency=input.Currency,Binding=profile.Binding,Revision=profile.Revision,ProposedBy=user};
if(!await store.TryInsertPayment(p))throw new PaymentConflict("This payment reference already exists. Review its history instead of creating another invoice.");return p;
}
async Task Save(PaymentRequest p,string state,string detail)
{
long old=p.Version;p.Version++;p.State=state;p.Detail=detail;p.UpdatedAt=DateTime.UtcNow;
if(!await store.Replace(p.HotelId,p.Id,old,p))throw new PaymentConflict("The payment request changed elsewhere. Refresh its status.");
}
async Task Enabled(string hotel,NmiProfile profile){if(!profile.CreatesEnabled||(await store.Get<Hotel>(hotel,hotel))?.PaymentsEnabled!=true)throw new PaymentInvalid("Payment creation is disabled for this hotel.");}
public async Task<PaymentRequest> Create(PaymentRequest p,long version,string user,bool approved,CancellationToken ct)
{
if(p.Version!=version||p.State!="Review")throw new PaymentConflict("Only a current proposal can be approved once.");
if(!approved)throw new PaymentInvalid("Approve the recipient, amount and NMI customer email before creating an invoice.");
if(p.ExpiresAt<DateTime.UtcNow)throw new PaymentConflict("The proposal expired. Cancel it and prepare a new payment reference.");
var profile=Profile(p.HotelId);if(profile.Revision!=p.Revision)throw new PaymentConflict("Merchant configuration changed. Prepare a new reviewed request.");await Enabled(p.HotelId,profile);
p.ApprovedBy=user;await Save(p,"Creating","Creating the approved NMI invoice. NMI may email the customer.");
using var deadline=CancellationTokenSource.CreateLinkedTokenSource(ct);deadline.CancelAfter(TimeSpan.FromSeconds(90));bool submitted=false;
try
{
await Enabled(p.HotelId,profile);deadline.Token.ThrowIfCancellationRequested();submitted=true;
var result=await nmi.Create(profile,p,deadline.Token);p.InvoiceId=NmiInvoices.Id(result);
await Save(p,"Creating","Invoice identity received; checking the recorded details.");
var read=await nmi.Get(profile,p.InvoiceId,deadline.Token);await Observe(p,read);
}
catch(Exception){await Save(p,submitted?"NeedsReview":"NotCreated",submitted?"Creation outcome needs verification. NMI may have created or emailed the invoice. Do not repeat it.":"No invoice creation was submitted.");}
return p;
}
async Task Observe(PaymentRequest p,JsonElement read)
{
var state=NmiInvoices.Verify(p,read);p.InvoiceId=NmiInvoices.Id(read);p.CheckedAt=DateTime.UtcNow;
await Save(p,state,state=="Paid"?"NMI reports this invoice paid. This is not bank settlement confirmation and does not create or update a PMS booking.":"Invoice details and current status were read from NMI. No payment or email was initiated by this check.");
}
public async Task<PaymentRequest> Check(PaymentRequest p,long version,CancellationToken ct)
{
if(p.Version!=version||p.State is "Review" or "Cancelled" or "NotCreated"||p.State=="Creating"&&p.UpdatedAt>DateTime.UtcNow.AddMinutes(-5))throw new PaymentConflict("Refresh the request. Interrupted creation can be checked after five minutes.");
var profile=Profile(p.HotelId);if(p.Binding!=profile.Binding)throw new PaymentConflict("Restore the original merchant binding before checking this invoice.");
using var deadline=CancellationTokenSource.CreateLinkedTokenSource(ct);deadline.CancelAfter(TimeSpan.FromSeconds(90));
try {var result=p.InvoiceId.Length>0?await nmi.Get(profile,p.InvoiceId,deadline.Token):await nmi.Find(profile,p,deadline.Token);await Observe(p,result);}
catch(Exception){await Save(p,"NeedsReview","The invoice could not be verified. Check the merchant portal; no creation, email or payment was repeated.");}
return p;
}
public async Task<PaymentRequest> Cancel(PaymentRequest p,long version)
{
if(p.Version!=version||p.State!="Review")throw new PaymentConflict("Only a proposal that has not started can be cancelled here.");await Save(p,"Cancelled","Proposal cancelled before contacting NMI. The reference remains reserved for audit history.");return p;
}
}
+6
View File
@@ -14,6 +14,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);
if (builder.Configuration["Payments:ConfigFile"] is { Length: > 0 } paymentConfigFile) builder.Configuration.AddJsonFile(paymentConfigFile,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);
@@ -31,6 +32,8 @@ builder.Services.AddHttpClient<AiDrafts>(c => c.Timeout = TimeSpan.FromSeconds(6
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.AddHttpClient<NmiInvoices>(c=>c.Timeout=TimeSpan.FromSeconds(25)).ConfigurePrimaryHttpMessageHandler(()=>new HttpClientHandler{AllowAutoRedirect=false});
builder.Services.AddTransient<PaymentWork>();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
{
o.Cookie.Name = "guestops.session"; o.Cookie.HttpOnly = true; o.Cookie.SameSite = SameSiteMode.Lax;
@@ -87,6 +90,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 (PaymentInvalid ex) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
catch (PaymentConflict ex) { ctx.Response.StatusCode = 409; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
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." }); }
@@ -124,6 +129,7 @@ app.MapPost("/api/auth/logout", async (HttpContext c, CancellationToken _) => {
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);
PaymentEndpoints.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) =>
{
+17 -1
View File
@@ -22,6 +22,7 @@ public interface IStore
Task Import(Conversation message);
Task<List<Conversation>> Deliveries();
Task<bool> TryInsertPmsChange(PmsChange change);
Task<bool> TryInsertPayment(PaymentRequest payment);
}
public sealed class MongoStore : IStore
{
@@ -42,6 +43,8 @@ public sealed class MongoStore : IStore
}
public async Task Initialize()
{
await Collection<PaymentRequest>().Indexes.CreateOneAsync(new CreateIndexModel<PaymentRequest>(Builders<PaymentRequest>.IndexKeys.Ascending(x=>x.HotelId).Ascending(x=>x.Reference),new(){Unique=true}));
await Collection<PaymentRequest>().Indexes.CreateOneAsync(new CreateIndexModel<PaymentRequest>(Builders<PaymentRequest>.IndexKeys.Ascending(x=>x.HotelId).Descending(x=>x.UpdatedAt)));
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)}));
@@ -57,7 +60,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"));
if (typeof(T) == typeof(PmsChange) || typeof(T) == typeof(PaymentRequest)) 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();
@@ -98,6 +101,11 @@ public sealed class MongoStore : IStore
try { await Insert(message); }
catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey) { /* already durable */ }
}
public async Task<bool> TryInsertPayment(PaymentRequest payment)
{
try { await Insert(payment);return true; }
catch(MongoWriteException ex) when(ex.WriteError.Category==ServerErrorCategory.DuplicateKey){return false;}
}
public async Task<bool> TryInsertPmsChange(PmsChange change)
{
try { await Insert(change);return true; }
@@ -108,6 +116,14 @@ public sealed class MongoStore : IStore
// Explicit Development-only preview store. Production never falls back to this.
public sealed class PreviewStore : IStore
{
public Task<bool> TryInsertPayment(PaymentRequest payment)
{
lock(gate)
{
if(rows.Where(x=>x.Key.StartsWith("PaymentRequest:")).Select(x=>Clone<PaymentRequest>(x.Value)).Any(x=>x.HotelId==payment.HotelId&&x.Reference==payment.Reference))return Task.FromResult(false);
return Task.FromResult(rows.TryAdd(Key<PaymentRequest>(payment.Id),Json(payment)));
}
}
public Task<bool> TryInsertPmsChange(PmsChange change)
{
lock(gate)