Build private multi-hotel web foundation with MongoDB, Gmail import and Linux deployment

This commit is contained in:
wolf-demon
2026-09-09 14:16:34 +01:00
parent dec97954c9
commit 49d02be623
37 changed files with 2598 additions and 2 deletions
+22
View File
@@ -0,0 +1,22 @@
namespace GuestOps.Web;
public static class Demo
{
public static async Task<StaffUser> Seed(IStore store)
{
var hotel = new Hotel { Name = "The Willow House", Signature = "Warm regards,\nThe Willow House team" }; hotel.HotelId = hotel.Id;
var user = new StaffUser { HotelId = hotel.Id, Name = "Alex Morgan", Email = hotel.Id + "@example.invalid" };
await store.Insert(hotel); await store.Insert(user);
var questions = new[] {
("Emma Wilson", "A little question before our weekend stay", "Hello! We're looking forward to staying with you on Friday. Is there somewhere to park our car, and do we need to book a space?\n\nMany thanks,\nEmma", "Parking", "Hello Emma,\n\nWe're looking forward to welcoming you on Friday. Complimentary parking is available in our courtyard, subject to availability. There is no need to reserve a space.\n\nWarm regards,\nThe Willow House team"),
("James & Sophie", "Arriving a little earlier on Saturday", "Hi there, our train gets in at 12:30. Would it be possible to leave our bags with you before check-in? Thank you!", "Arrival", ""),
("Oliver Brooks", "Changing the dates of our booking", "Our plans have changed. Could we move reservation WH-2481 to the following weekend? Please let me know whether there is a charge.", "Booking change", ""),
("Charlotte Reed", "Breakfast options for our stay", "Good morning, do you offer vegetarian breakfast options? My partner also has a nut allergy.", "Dietary request", ""),
("Amelia Patel", "Thank you for a lovely stay", "We had a wonderful weekend. Please pass on our thanks to the team!", "General", "")
};
for (int i = 0; i < questions.Length; i++) { var q = questions[i]; await store.Insert(new Conversation { HotelId = hotel.Id, ProviderMessageId = Guid.NewGuid().ToString("N"), From = q.Item1 + " <guest@example.invalid>", Subject = q.Item2, Body = q.Item3, Category = q.Item4, Draft = q.Item5, Status = i == 0 ? "DraftReady" : i == 4 ? "Completed" : "NeedsAttention", ReceivedAt = DateTime.UtcNow.AddMinutes(-i * 28 - 12), Note = i == 2 ? "A booking change needs a member of your team." : i == 3 ? "Check dietary requirements with the hotel team." : "" }); }
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" });
return user;
}
}
+79
View File
@@ -0,0 +1,79 @@
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;
namespace GuestOps.Web;
public sealed class GoogleMailbox(HttpClient http, IConfiguration config, IStore store, IDataProtectionProvider protection)
{
private readonly IDataProtector protector = protection.CreateProtector("GoogleMailbox.refresh.v1");
private string ClientId => config["Google:ClientId"] ?? "";
private string ClientSecret => config["Google:ClientSecret"] ?? "";
private string Callback => (config["PublicUrl"] ?? "https://sandbox-guestops.futuresens.co.uk").TrimEnd('/') + "/api/integrations/google/callback";
public bool Configured => ClientId.Length > 0 && ClientSecret.Length > 0;
public string AuthorizationUrl(string state) => "https://accounts.google.com/o/oauth2/v2/auth?" + string.Join("&", new Dictionary<string,string> {
["client_id"] = ClientId, ["redirect_uri"] = Callback, ["response_type"] = "code", ["scope"] = "https://www.googleapis.com/auth/gmail.readonly", ["access_type"] = "offline", ["prompt"] = "consent", ["state"] = state
}.Select(x => Uri.EscapeDataString(x.Key) + "=" + Uri.EscapeDataString(x.Value)));
async Task<JsonElement> Token(Dictionary<string, string> data, CancellationToken ct = default)
{
data["client_id"] = ClientId; data["client_secret"] = ClientSecret;
using var response = await http.PostAsync("https://oauth2.googleapis.com/token", new FormUrlEncodedContent(data), ct);
response.EnsureSuccessStatusCode();
return JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct)).RootElement.Clone();
}
async Task<JsonElement> Read(string path, string token, CancellationToken ct = default)
{
using var request = new HttpRequestMessage(HttpMethod.Get, "https://gmail.googleapis.com/gmail/v1/users/me/" + path);
request.Headers.Authorization = new("Bearer", token);
using var response = await http.SendAsync(request, ct); response.EnsureSuccessStatusCode();
return JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct)).RootElement.Clone();
}
public async Task Connect(string hotel, string code)
{
if (string.IsNullOrWhiteSpace(code)) throw new InvalidOperationException("No authorization code.");
var tokens = await Token(new() { ["code"] = code, ["redirect_uri"] = Callback, ["grant_type"] = "authorization_code" });
var profile = await Read("profile", tokens.GetProperty("access_token").GetString()!);
var email = profile.GetProperty("emailAddress").GetString()!.ToLowerInvariant();
var prior = (await store.List<Mailbox>(hotel)).SingleOrDefault(x => x.Email == email);
var mailbox = prior ?? new Mailbox { HotelId = hotel, Email = email };
// No token reuse across hotels. Mongo's unique mailbox-email index prevents
// accidental connection of one shared mailbox to two hotel workspaces.
mailbox.ProtectedRefreshToken = protector.Protect(tokens.GetProperty("refresh_token").GetString()!);
mailbox.Status = "Connected"; mailbox.SyncError = "";
await store.SaveMailbox(mailbox);
}
public async Task Sync(Mailbox mailbox, CancellationToken ct)
{
var tokens = await Token(new() { ["refresh_token"] = protector.Unprotect(mailbox.ProtectedRefreshToken), ["grant_type"] = "refresh_token" }, ct);
var token = tokens.GetProperty("access_token").GetString()!;
var after = new DateTimeOffset(mailbox.WindowStart).ToUnixTimeSeconds();
var before = new DateTimeOffset(mailbox.WindowEnd).ToUnixTimeSeconds();
var query = Uri.EscapeDataString($"in:inbox after:{after} before:{before}");
var path = "messages?maxResults=25&q=" + query + (mailbox.PageToken.Length > 0 ? "&pageToken=" + Uri.EscapeDataString(mailbox.PageToken) : "");
var page = await Read(path, token, ct);
if (page.TryGetProperty("messages", out var items)) foreach (var item in items.EnumerateArray())
{
var id = item.GetProperty("id").GetString()!;
var message = await Read("messages/" + Uri.EscapeDataString(id) + "?format=full", token, ct);
var payload = message.GetProperty("payload");
string Header(string name) => payload.GetProperty("headers").EnumerateArray().Where(x => string.Equals(x.GetProperty("name").GetString(), name, StringComparison.OrdinalIgnoreCase)).Select(x => x.GetProperty("value").GetString()).FirstOrDefault() ?? "";
var auto = Header("Auto-Submitted");
if ((auto.Length > 0 && auto != "no") || Header("List-Id").Length > 0 || Header("Return-Path").Trim() == "<>") continue;
var body = PlainText(payload);
var row = new Conversation { HotelId = mailbox.HotelId, MailboxId = mailbox.Id, ProviderMessageId = id, ProviderThreadId = message.GetProperty("threadId").GetString()!, From = Header("From"), Subject = Header("Subject"), Body = body.Length > 0 ? body[..Math.Min(body.Length, 30000)] : "This message has no plain-text body. Open it in Gmail to read it.", ReceivedAt = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(message.GetProperty("internalDate").GetString()!)).UtcDateTime };
await store.Import(row); // deduplicated before advancing the page checkpoint
}
mailbox.PageToken = page.TryGetProperty("nextPageToken", out var next) ? next.GetString()! : "";
if (mailbox.PageToken.Length == 0) { mailbox.WindowStart = mailbox.WindowEnd.AddMinutes(-5); mailbox.WindowEnd = DateTime.UtcNow; }
mailbox.LastSyncAt = DateTime.UtcNow; mailbox.SyncError = "";
await store.SaveSync(mailbox);
}
static string PlainText(JsonElement payload)
{
if (payload.TryGetProperty("mimeType", out var mime) && mime.GetString() == "text/plain" && payload.TryGetProperty("body", out var body) && body.TryGetProperty("data", out var data))
{
var raw = data.GetString()!.Replace('-', '+').Replace('_', '/'); raw = raw.PadRight((raw.Length + 3) / 4 * 4, '=');
return Encoding.UTF8.GetString(Convert.FromBase64String(raw));
}
return payload.TryGetProperty("parts", out var parts) ? string.Join("\n", parts.EnumerateArray().Select(PlainText).Where(x => x.Length > 0)) : "";
}
}
+1
View File
@@ -0,0 +1 @@
<Project Sdk="Microsoft.NET.Sdk.Web"><ItemGroup><ProjectReference Include="../GuestOps.Core/GuestOps.Core.csproj"/><PackageReference Include="MongoDB.Driver" Version="3.11.1"/></ItemGroup></Project>
+82
View File
@@ -0,0 +1,82 @@
using MongoDB.Bson.Serialization.Attributes;
namespace GuestOps.Web;
public interface ITenantDocument { string Id { get; set; } string HotelId { get; set; } }
public abstract class TenantDocument : ITenantDocument
{
[BsonId] public string Id { get; set; } = Guid.NewGuid().ToString("N");
public string HotelId { get; set; } = "";
}
public class Hotel : TenantDocument
{
public string Name { get; set; } = "";
public string Timezone { get; set; } = "Europe/London";
public string Signature { get; set; } = "Warm regards,\nThe reservations team";
public string ReplyMode { get; set; } = "DraftOnly";
public long Version { get; set; }
}
public class StaffUser : TenantDocument
{
public string Email { get; set; } = "";
public string Name { get; set; } = "";
public string PasswordHash { get; set; } = "";
public string Role { get; set; } = "Owner";
public bool Active { get; set; } = true;
}
public class KnowledgeEntry : TenantDocument
{
public string Title { get; set; } = "";
public string Category { get; set; } = "General";
public string Answer { get; set; } = "";
public string Keywords { get; set; } = "";
public bool Approved { get; set; }
public long Version { get; set; }
}
public class Conversation : TenantDocument
{
public string MailboxId { get; set; } = "";
public string ProviderMessageId { get; set; } = "";
public string ProviderThreadId { get; set; } = "";
public string From { get; set; } = "";
public string Subject { get; set; } = "";
public string Body { get; set; } = "";
public DateTime ReceivedAt { get; set; } = DateTime.UtcNow;
public string Status { get; set; } = "NeedsAttention";
public string Draft { get; set; } = "";
public string Category { get; set; } = "General";
public string Note { get; set; } = "";
public long Version { get; set; }
}
public class Mailbox : TenantDocument
{
public string Email { get; set; } = "";
public string ProtectedRefreshToken { get; set; } = "";
public string Status { get; set; } = "Connected";
public DateTime? LastSyncAt { get; set; }
public string SyncError { get; set; } = "";
public string PageToken { get; set; } = "";
public DateTime WindowStart { get; set; } = DateTime.UtcNow.AddDays(-7);
public DateTime WindowEnd { get; set; } = DateTime.UtcNow;
}
public class OAuthRequest : TenantDocument
{
public string UserId { get; set; } = "";
public DateTime ExpiresAt { get; set; }
}
public class Activity : TenantDocument
{
public DateTime At { get; set; } = DateTime.UtcNow;
public string UserName { get; set; } = "";
public string Action { get; set; } = "";
}
public class WorkerLease
{
[BsonId] public string Id { get; set; } = "";
public string Owner { get; set; } = "";
public DateTime Until { get; set; }
}
public record LoginInput(string Email, string Password);
public record SettingsInput(string Name, string Timezone, string Signature, long Version);
public record DraftInput(string Draft, long Version);
public record StatusInput(string Status, long Version);
public record KnowledgeInput(string Title, string Category, string Answer, string Keywords, bool Approved, long Version);
+184
View File
@@ -0,0 +1,184 @@
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.RateLimiting;
using GuestOps.Web;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders(); builder.Logging.AddConsole();
builder.Logging.AddFilter("Microsoft.AspNetCore.Hosting.Diagnostics", LogLevel.Warning);
builder.Logging.AddFilter("System.Net.Http.HttpClient", LogLevel.Warning);
var preview = builder.Configuration.GetValue<bool>("Preview");
if (preview && !builder.Environment.IsDevelopment()) throw new InvalidOperationException("Preview mode is Development-only.");
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 128 * 1024);
var protection = builder.Services.AddDataProtection().SetApplicationName("GuestOps-Web");
var keyPath = builder.Configuration["Keys:Path"];
if (!preview && string.IsNullOrWhiteSpace(keyPath)) throw new InvalidOperationException("Keys:Path must point to a persistent private directory.");
if (keyPath != null) protection.PersistKeysToFileSystem(new DirectoryInfo(keyPath));
builder.Services.AddSingleton<IStore>(s => preview ? new PreviewStore() : new MongoStore(s.GetRequiredService<IConfiguration>()));
builder.Services.AddSingleton<IPasswordHasher<StaffUser>, PasswordHasher<StaffUser>>();
builder.Services.AddHttpClient<GoogleMailbox>(c => c.Timeout = TimeSpan.FromSeconds(25));
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
{
o.Cookie.Name = "guestops.session"; o.Cookie.HttpOnly = true; o.Cookie.SameSite = SameSiteMode.Lax;
o.Cookie.SecurePolicy = preview ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always;
o.ExpireTimeSpan = TimeSpan.FromHours(8); o.SlidingExpiration = false;
o.Events.OnRedirectToLogin = c => { c.Response.StatusCode = 401; return Task.CompletedTask; };
o.Events.OnRedirectToAccessDenied = c => { c.Response.StatusCode = 403; return Task.CompletedTask; };
o.Events.OnValidatePrincipal = async c =>
{
var hotel = c.Principal?.FindFirstValue("hotel"); var id = c.Principal?.FindFirstValue(ClaimTypes.NameIdentifier);
var user = hotel == null || id == null ? null : await c.HttpContext.RequestServices.GetRequiredService<IStore>().Get<StaffUser>(hotel, id);
if (user == null || !user.Active || user.Role != c.Principal!.FindFirstValue(ClaimTypes.Role)) c.RejectPrincipal();
};
});
builder.Services.AddAuthorization(o => o.AddPolicy("Owner", p => p.RequireRole("Owner")));
builder.Services.AddAntiforgery(o => { o.HeaderName = "X-CSRF-TOKEN"; o.Cookie.Name = "guestops.csrf"; o.Cookie.HttpOnly = true; o.Cookie.SameSite = SameSiteMode.Strict; o.Cookie.SecurePolicy = preview ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always; });
builder.Services.AddRateLimiter(o =>
{
o.RejectionStatusCode = 429;
o.AddPolicy("login", context => RateLimitPartition.GetFixedWindowLimiter(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new() { PermitLimit = 10, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }));
});
var app = builder.Build();
var store = app.Services.GetRequiredService<IStore>();
await store.Initialize();
if (args.Contains("--bootstrap"))
{
var email = Environment.GetEnvironmentVariable("BOOTSTRAP_EMAIL")?.Trim().ToLowerInvariant() ?? "";
var password = Environment.GetEnvironmentVariable("BOOTSTRAP_PASSWORD") ?? "";
var hotelName = Environment.GetEnvironmentVariable("BOOTSTRAP_HOTEL") ?? "";
if (!Input.Email(email) || password.Length < 14 || hotelName.Length < 2) throw new InvalidOperationException("Set BOOTSTRAP_EMAIL, BOOTSTRAP_PASSWORD (14+ characters), and BOOTSTRAP_HOTEL.");
if (await store.FindLogin(email) != null) throw new InvalidOperationException("Account already exists; bootstrap does not reset credentials.");
var hotel = new Hotel { Name = hotelName }; hotel.HotelId = hotel.Id;
var user = new StaffUser { HotelId = hotel.Id, Email = email, Name = "Hotel owner" };
user.PasswordHash = app.Services.GetRequiredService<IPasswordHasher<StaffUser>>().HashPassword(user, password);
await store.Insert(hotel); await store.Insert(user);
Console.WriteLine("Hotel and owner account created."); return;
}
app.Use(async (ctx, next) =>
{
ctx.Response.Headers["X-Content-Type-Options"] = "nosniff";
ctx.Response.Headers["Referrer-Policy"] = "same-origin";
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 (AntiforgeryValidationException) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = "Your session needs refreshing. Reload the page and try again." }); }
catch (Exception ex)
{
app.Logger.LogError("Request failed ({Type}), trace {Trace}", ex.GetType().Name, ctx.TraceIdentifier);
if (!ctx.Response.HasStarted) { ctx.Response.StatusCode = 500; await ctx.Response.WriteAsJsonAsync(new { error = "The request could not be completed. Please try again.", trace = ctx.TraceIdentifier }); }
}
});
app.UseAuthentication(); app.UseAuthorization(); app.UseRateLimiter();
app.Use(async (ctx, next) =>
{
if (ctx.Request.Path.StartsWithSegments("/api") && !HttpMethods.IsGet(ctx.Request.Method) && !HttpMethods.IsHead(ctx.Request.Method))
await ctx.RequestServices.GetRequiredService<IAntiforgery>().ValidateRequestAsync(ctx);
await next();
});
app.MapGet("/health", () => Results.Ok(new { status = "ready" }));
app.MapGet("/api/session", (HttpContext c, IAntiforgery csrf) => Results.Ok(new
{
preview, csrfToken = csrf.GetAndStoreTokens(c).RequestToken,
user = c.User.Identity?.IsAuthenticated == true ? new { id = c.User.FindFirstValue(ClaimTypes.NameIdentifier), name = c.User.Identity.Name, role = c.User.FindFirstValue(ClaimTypes.Role), hotelId = c.User.FindFirstValue("hotel") } : null
}));
app.MapPost("/api/auth/login", async (LoginInput input, HttpContext c, IPasswordHasher<StaffUser> hasher) =>
{
if (input.Email.Length > 254 || input.Password.Length > 256) return Results.BadRequest(new { error = "Invalid credentials." });
var user = await store.FindLogin(input.Email.Trim().ToLowerInvariant());
// Verify a dummy hash too so unknown accounts do not have a fast password path.
var checkUser = user ?? new StaffUser();
var hash = user?.PasswordHash ?? Input.DummyHash;
if (hasher.VerifyHashedPassword(checkUser, hash, input.Password) == PasswordVerificationResult.Failed || user?.Active != true)
return Results.Json(new { error = "Email or password is incorrect." }, statusCode: 401);
await Session.SignIn(c, user); return Results.Ok();
}).RequireRateLimiting("login");
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();
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) =>
{
if (!Input.Text(input.Name, 2, 120) || !Input.Text(input.Signature, 0, 2000)) return Results.BadRequest(new { error = "Enter a hotel name and a signature under 2,000 characters." });
try { _ = TimeZoneInfo.FindSystemTimeZoneById(input.Timezone); } catch { return Results.BadRequest(new { error = "Choose a valid timezone." }); }
var hotel = await store.Get<Hotel>(Session.Hotel(c), Session.Hotel(c)); if (hotel == null) return Results.NotFound();
hotel.Name = input.Name.Trim(); hotel.Signature = input.Signature; hotel.Timezone = input.Timezone; 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 hotel settings"); return Results.Ok(hotel);
}).RequireAuthorization("Owner");
api.MapGet("/conversations", async (HttpContext c, CancellationToken _) => Results.Ok((await store.List<Conversation>(Session.Hotel(c))).OrderByDescending(x => x.ReceivedAt)));
api.MapPut("/conversations/{id}/draft", async (string id, DraftInput input, HttpContext c) =>
{
if (!Input.Text(input.Draft, 0, 20000)) return Results.BadRequest(new { error = "Draft must be under 20,000 characters." });
var item = await store.Get<Conversation>(Session.Hotel(c), id); if (item == null) return Results.NotFound();
item.Draft = input.Draft; item.Version = input.Version + 1; if (item.Status != "Completed") item.Status = input.Draft.Length > 0 ? "DraftReady" : "NeedsAttention";
if (!await store.Replace(item.HotelId, id, input.Version, item)) return Input.Conflict();
await Session.Audit(store, c, "Saved a reply draft"); return Results.Ok(item);
});
api.MapPut("/conversations/{id}/status", async (string id, StatusInput input, HttpContext c) =>
{
if (input.Status is not ("Completed" or "NeedsAttention")) return Results.BadRequest();
var item = await store.Get<Conversation>(Session.Hotel(c), id); if (item == null) return Results.NotFound();
item.Status = input.Status; item.Version = input.Version + 1;
if (!await store.Replace(item.HotelId, id, input.Version, item)) return Input.Conflict();
await Session.Audit(store, c, input.Status == "Completed" ? "Resolved a conversation" : "Reopened a conversation"); return Results.Ok(item);
});
api.MapGet("/knowledge", async (HttpContext c, CancellationToken _) => Results.Ok(await store.List<KnowledgeEntry>(Session.Hotel(c))));
api.MapPost("/knowledge", async (KnowledgeInput input, HttpContext c) =>
{
if (!Input.Knowledge(input)) return Results.BadRequest(new { error = "Enter a title and answer within the allowed lengths." });
var item = new KnowledgeEntry { HotelId = Session.Hotel(c), Title = input.Title, Category = input.Category, Answer = input.Answer, Keywords = input.Keywords, Approved = input.Approved };
await store.Insert(item); await Session.Audit(store, c, "Added a hotel knowledge entry"); return Results.Ok(item);
}).RequireAuthorization("Owner");
api.MapPut("/knowledge/{id}", async (string id, KnowledgeInput input, HttpContext c) =>
{
if (!Input.Knowledge(input)) return Results.BadRequest();
var item = await store.Get<KnowledgeEntry>(Session.Hotel(c), id); if (item == null) return Results.NotFound();
item.Title = input.Title; item.Category = input.Category; item.Answer = input.Answer; item.Keywords = input.Keywords; item.Approved = input.Approved; item.Version = input.Version + 1;
if (!await store.Replace(item.HotelId, id, input.Version, item)) return Input.Conflict();
await Session.Audit(store, c, "Updated hotel knowledge"); return Results.Ok(item);
}).RequireAuthorization("Owner");
api.MapGet("/activity", async (HttpContext c, CancellationToken _) => Results.Ok((await store.List<Activity>(Session.Hotel(c))).OrderByDescending(x => x.At).Take(100)));
api.MapGet("/mailboxes", async (HttpContext c, GoogleMailbox google) => Results.Ok(new { configured = !preview && google.Configured, items = (await store.List<Mailbox>(Session.Hotel(c))).Select(x => new { x.Id, x.Email, x.Status, x.LastSyncAt, x.SyncError }) }));
api.MapPost("/integrations/google/connect", async (HttpContext c, GoogleMailbox google) =>
{
if (preview || !google.Configured) return Results.BadRequest(new { error = "Google connection has not been configured by the administrator." });
var state = new OAuthRequest { Id = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)), HotelId = Session.Hotel(c), UserId = c.User.FindFirstValue(ClaimTypes.NameIdentifier)!, ExpiresAt = DateTime.UtcNow.AddMinutes(10) };
await store.Insert(state); return Results.Ok(new { url = google.AuthorizationUrl(state.Id) });
}).RequireAuthorization("Owner");
api.MapGet("/integrations/google/callback", async (HttpContext c, GoogleMailbox google) =>
{
if (preview) return Results.BadRequest();
var state = await store.ConsumeOAuth(c.Request.Query["state"].ToString(), Session.Hotel(c), c.User.FindFirstValue(ClaimTypes.NameIdentifier)!);
if (state == null) return Results.BadRequest(new { error = "The connection request expired. Start again from Settings." });
if (c.Request.Query.ContainsKey("error")) return Results.Redirect("/settings?google=cancelled");
try { await google.Connect(Session.Hotel(c), c.Request.Query["code"].ToString()); await Session.Audit(store, c, "Connected Google mailbox"); }
catch { return Results.Redirect("/settings?google=failed"); }
return Results.Redirect("/settings?google=connected");
}).RequireAuthorization("Owner");
app.UseDefaultFiles(); app.UseStaticFiles();
app.MapFallbackToFile("index.html");
app.Run();
namespace GuestOps.Web
{
public static class Session
{
public static string Hotel(HttpContext c) => c.User.FindFirstValue("hotel") ?? throw new InvalidOperationException("Missing hotel membership");
public static Task SignIn(HttpContext c, StaffUser u) => c.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, u.Id), new Claim(ClaimTypes.Name, u.Name), new Claim(ClaimTypes.Role, u.Role), new Claim("hotel", u.HotelId) }, CookieAuthenticationDefaults.AuthenticationScheme)));
public static Task Audit(IStore store, HttpContext c, string action) => store.Insert(new Activity { HotelId = Hotel(c), UserName = c.User.Identity?.Name ?? "Staff", Action = action });
}
public static class Input
{
public static readonly string DummyHash = new PasswordHasher<StaffUser>().HashPassword(new(), Convert.ToHexString(RandomNumberGenerator.GetBytes(32)));
public static bool Text(string? s, int min, int max) => s != null && s.Trim().Length >= min && s.Length <= max;
public static bool Email(string s) => System.Net.Mail.MailAddress.TryCreate(s, out var address) && address.Address == s;
public static bool Knowledge(KnowledgeInput s) => Text(s.Title, 2, 120) && Text(s.Answer, 2, 5000) && Text(s.Category, 1, 50) && Text(s.Keywords, 0, 300);
public static IResult Conflict() => Results.Conflict(new { error = "Someone changed this record. Reload it before saving again." });
}
}
+126
View File
@@ -0,0 +1,126 @@
using System.Collections.Concurrent;
using MongoDB.Driver;
namespace GuestOps.Web;
// All application reads/writes require a server-derived hotel ID. Global access is
// confined to authentication and the mailbox worker, not exposed as query parameters.
public interface IStore
{
Task Initialize();
Task<List<T>> List<T>(string hotel) where T : TenantDocument;
Task<T?> Get<T>(string hotel, string id) where T : TenantDocument;
Task Insert<T>(T document) where T : TenantDocument;
Task<bool> Replace<T>(string hotel, string id, long version, T document) where T : TenantDocument;
Task Delete<T>(string hotel, string id) where T : TenantDocument;
Task<StaffUser?> FindLogin(string email);
Task<OAuthRequest?> ConsumeOAuth(string id, string hotel, string user);
Task<List<Mailbox>> Mailboxes();
Task SaveMailbox(Mailbox mailbox);
Task SaveSync(Mailbox mailbox);
Task<bool> TryLease(string id, string owner);
Task ReleaseLease(string id, string owner);
Task Import(Conversation message);
}
public sealed class MongoStore : IStore
{
private readonly IMongoDatabase db;
public MongoStore(IConfiguration config)
{
var connection = config["Mongo:ConnectionString"] ?? throw new InvalidOperationException("Mongo:ConnectionString is required.");
var settings = MongoClientSettings.FromConnectionString(connection);
settings.ServerSelectionTimeout = TimeSpan.FromSeconds(8);
db = new MongoClient(settings).GetDatabase(config["Mongo:Database"] ?? "guestops");
}
IMongoCollection<T> Collection<T>() => db.GetCollection<T>(typeof(T).Name.ToLowerInvariant());
FilterDefinition<T> Scope<T>(string hotel) where T : TenantDocument
{
if (string.IsNullOrWhiteSpace(hotel)) throw new InvalidOperationException("Hotel scope required.");
return Builders<T>.Filter.Eq(x => x.HotelId, hotel);
}
public async Task Initialize()
{
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)));
await Collection<Mailbox>().Indexes.CreateOneAsync(new CreateIndexModel<Mailbox>(Builders<Mailbox>.IndexKeys.Ascending(x => x.Email), new() { Unique = true }));
await Collection<OAuthRequest>().Indexes.CreateOneAsync(new CreateIndexModel<OAuthRequest>(Builders<OAuthRequest>.IndexKeys.Ascending(x => x.ExpiresAt), new() { ExpireAfter = TimeSpan.Zero }));
}
public Task<List<T>> List<T>(string hotel) where T : TenantDocument
{
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"));
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();
public Task Insert<T>(T document) where T : TenantDocument
{
_ = Scope<T>(document.HotelId);
return Collection<T>().InsertOneAsync(document);
}
public async Task<bool> Replace<T>(string hotel, string id, long version, T document) where T : TenantDocument
{
if (document.HotelId != hotel || document.Id != id) throw new InvalidOperationException("Invalid document scope.");
var result = await Collection<T>().ReplaceOneAsync(Scope<T>(hotel) & Builders<T>.Filter.Eq(x => x.Id, id) & Builders<T>.Filter.Eq("Version", version), document);
return result.ModifiedCount == 1;
}
public async Task Delete<T>(string hotel, string id) where T : TenantDocument => await Collection<T>().DeleteOneAsync(Scope<T>(hotel) & Builders<T>.Filter.Eq(x => x.Id, id));
public async Task<StaffUser?> FindLogin(string email) => await Collection<StaffUser>().Find(x => x.Email == email).FirstOrDefaultAsync();
public async Task<OAuthRequest?> ConsumeOAuth(string id, string hotel, string user) => await Collection<OAuthRequest>().FindOneAndDeleteAsync(x => x.Id == id && x.HotelId == hotel && x.UserId == user && x.ExpiresAt > DateTime.UtcNow);
public Task<List<Mailbox>> Mailboxes() => Collection<Mailbox>().Find(x => x.Status == "Connected").ToListAsync();
public async Task SaveMailbox(Mailbox mailbox) => await Collection<Mailbox>().ReplaceOneAsync(x => x.HotelId == mailbox.HotelId && x.Id == mailbox.Id, mailbox, new ReplaceOptions { IsUpsert = true });
public async Task SaveSync(Mailbox mailbox) => await Collection<Mailbox>().UpdateOneAsync(
x => x.HotelId == mailbox.HotelId && x.Id == mailbox.Id && x.ProtectedRefreshToken == mailbox.ProtectedRefreshToken,
Builders<Mailbox>.Update.Set(x => x.LastSyncAt, mailbox.LastSyncAt).Set(x => x.SyncError, mailbox.SyncError)
.Set(x => x.PageToken, mailbox.PageToken).Set(x => x.WindowStart, mailbox.WindowStart).Set(x => x.WindowEnd, mailbox.WindowEnd));
public async Task<bool> TryLease(string id, string owner)
{
try
{
var result = await Collection<WorkerLease>().FindOneAndUpdateAsync(x => x.Id == id && x.Until < DateTime.UtcNow,
Builders<WorkerLease>.Update.Set(x => x.Owner, owner).Set(x => x.Until, DateTime.UtcNow.AddMinutes(5)), new() { IsUpsert = true, ReturnDocument = ReturnDocument.After });
return result.Owner == owner;
}
catch (MongoCommandException ex) when (ex.Code == 11000) { return false; }
catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey) { return false; }
}
public async Task ReleaseLease(string id, string owner) => await Collection<WorkerLease>().DeleteOneAsync(x => x.Id == id && x.Owner == owner);
public async Task Import(Conversation message)
{
try { await Insert(message); }
catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey) { /* already durable */ }
}
}
// Explicit Development-only preview store. Production never falls back to this.
public sealed class PreviewStore : IStore
{
private readonly ConcurrentDictionary<string, string> rows = new();
private readonly object gate = new();
static string Key<T>(string id) => typeof(T).Name + ":" + id;
static T Clone<T>(string text) => System.Text.Json.JsonSerializer.Deserialize<T>(text)!;
static string Json<T>(T value) => System.Text.Json.JsonSerializer.Serialize(value);
public Task Initialize() => Task.CompletedTask;
public Task<List<T>> List<T>(string hotel) where T : TenantDocument => Task.FromResult(rows.Where(x => x.Key.StartsWith(typeof(T).Name + ":")).Select(x => Clone<T>(x.Value)).Where(x => x.HotelId == hotel).ToList());
public async Task<T?> Get<T>(string hotel, string id) where T : TenantDocument => (await List<T>(hotel)).SingleOrDefault(x => x.Id == id);
public Task Insert<T>(T document) where T : TenantDocument { if (!rows.TryAdd(Key<T>(document.Id), Json(document))) throw new InvalidOperationException("Duplicate document"); return Task.CompletedTask; }
public Task<bool> Replace<T>(string hotel, string id, long version, T document) where T : TenantDocument
{
lock (gate)
{
if (!rows.TryGetValue(Key<T>(id), out var raw)) return Task.FromResult(false);
var old = Clone<T>(raw);
if (old.HotelId != hotel || document.HotelId != hotel || document.Id != id || (long)typeof(T).GetProperty("Version")!.GetValue(old)! != version) return Task.FromResult(false);
rows[Key<T>(id)] = Json(document); return Task.FromResult(true);
}
}
public async Task Delete<T>(string hotel, string id) where T : TenantDocument { if (await Get<T>(hotel, id) != null) rows.TryRemove(Key<T>(id), out _); }
public Task<StaffUser?> FindLogin(string email) => Task.FromResult(rows.Where(x => x.Key.StartsWith("StaffUser:")).Select(x => Clone<StaffUser>(x.Value)).SingleOrDefault(x => x.Email == email));
public Task<OAuthRequest?> ConsumeOAuth(string id, string hotel, string user) { lock(gate) { var x = rows.TryGetValue(Key<OAuthRequest>(id), out var raw) ? Clone<OAuthRequest>(raw) : null; if(x?.HotelId != hotel || x.UserId != user || x.ExpiresAt <= DateTime.UtcNow) return Task.FromResult<OAuthRequest?>(null); rows.TryRemove(Key<OAuthRequest>(id),out _); return Task.FromResult<OAuthRequest?>(x); } }
public Task<List<Mailbox>> Mailboxes() => Task.FromResult(new List<Mailbox>());
public Task SaveMailbox(Mailbox mailbox) => throw new InvalidOperationException("Real mailbox connections are unavailable in preview mode.");
public Task SaveSync(Mailbox mailbox) => throw new InvalidOperationException("Real mailbox connections are unavailable in preview mode.");
public Task<bool> TryLease(string id, string owner) => Task.FromResult(false);
public Task ReleaseLease(string id, string owner) => Task.CompletedTask;
public async Task Import(Conversation message) { if (!(await List<Conversation>(message.HotelId)).Any(x => x.MailboxId == message.MailboxId && x.ProviderMessageId == message.ProviderMessageId)) await Insert(message); }
}
+260
View File
@@ -0,0 +1,260 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using GuestOps.Models;
namespace GuestOps.Services;
/// <summary>
/// Shared prompt-builder and JSON-parser used by every AI provider
/// (Ollama, OpenAI, ...). Each provider just sends the prompt to its
/// model and feeds the raw text response into <see cref="BuildRowsFromJson"/>.
/// </summary>
public static class AiExtractionPrompt
{
/// <summary>Maximum email body characters embedded in the prompt.</summary>
private const int MaxBodyChars = 12_000;
public static string Build(ParsedBooking b) => Build(b, customAddendum: "");
public static string Build(ParsedBooking b, string customAddendum)
{
var cleanedBody = EmailBodyCleaner.Truncate(EmailBodyCleaner.Clean(b.EmailBody), MaxBodyChars);
var addendum = string.IsNullOrWhiteSpace(customAddendum)
? ""
: $"\nADDITIONAL HOTEL-SPECIFIC RULES (operator-supplied):\n{customAddendum.Trim()}\n";
return $$"""
You are an email parser for a hotel reservations team. Read the email below and
extract a JSON object that lists EVERY booking or amendment described.
A single email can describe multiple bookings (e.g. three different lead guests
in the same message), so always return an array even if only one item exists.
Do not invent fields. If a value is not mentioned, set it to null or "".
If the email is written in a language other than English, mentally translate it
before extracting and return all string fields in English (room types, rate plans
and product codes must stay verbatim - do NOT translate codes).
Use action = "quote_request" when the guest is ASKING FOR A PRICE / availability
rather than making or amending an existing booking. Typical phrasings:
"how much for...", "what would it cost...", "do you have a room for...",
"can you quote me...", "what's your rate for...". For quote_request, set
checkin + nights + adults/children + room_type (best guess from the email);
confirmation_number can be empty.
{{addendum}}
Output shape (return EXACTLY this object):
{
"actions": [
{
"action": one of [create, cancel, change_checkin, change_room,
change_rate, add_package, remove_package,
update_email, update_phone, update_comment,
send_invoice, quote_request, none],
"subject": string (copy of the email subject line),
"first_name": string,
"last_name": string,
"adults": integer,
"children": integer,
"original_checkin": "YYYY-MM-DD" or null (only for change-of-arrival),
"checkin": "YYYY-MM-DD" or null,
"nights": integer,
"rooms": integer,
"room_type": string,
"rate_plan": string,
"package_code": string,
"upsells": string (comma-separated extras),
"payment_guarantee": string,
"comment": string,
"email": string,
"phone": string,
"new_email": string (only for update_email),
"new_phone": string (only for update_phone),
"cancellation_reason": string (only for cancel),
"confirmation_number": string,
"opera_res_id": string,
"confidence": integer 0-100,
"rationale": one-sentence explanation
}
]
}
EMAIL SUBJECT: {{b.EmailSubject}}
EMAIL FROM: {{b.EmailFrom}}
EMAIL DATE: {{b.EmailDate:yyyy-MM-dd HH:mm}}
EMAIL BODY (cleaned):
---
{{cleanedBody}}
---
Respond ONLY with the JSON object.
""";
}
public static List<ParsedBooking> BuildRowsFromJson(string raw, ParsedBooking seed)
{
var result = new List<ParsedBooking>();
if (string.IsNullOrWhiteSpace(raw))
{
seed.Status = RowStatus.LowConfidence;
seed.StatusMessage = "Empty AI response";
result.Add(seed);
return result;
}
var jsonText = ExtractFirstJsonObject(raw);
JsonDocument doc;
try { doc = JsonDocument.Parse(jsonText); }
catch (Exception ex)
{
seed.Status = RowStatus.LowConfidence;
seed.StatusMessage = "AI returned invalid JSON: " + ex.Message;
result.Add(seed);
return result;
}
using (doc)
{
var root = doc.RootElement;
JsonElement actionsElement = default;
bool hasArray = false;
if (root.ValueKind == JsonValueKind.Object &&
root.TryGetProperty("actions", out actionsElement) &&
actionsElement.ValueKind == JsonValueKind.Array)
{
hasArray = true;
}
if (hasArray)
{
bool first = true;
foreach (var item in actionsElement.EnumerateArray())
{
var row = first ? seed : CloneSeed(seed);
ApplyJsonToBooking(item, row);
result.Add(row);
first = false;
}
if (result.Count == 0)
{
seed.Status = RowStatus.LowConfidence;
seed.StatusMessage = "AI returned no actions";
result.Add(seed);
}
}
else
{
ApplyJsonToBooking(root, seed);
result.Add(seed);
}
}
return result;
}
private static ParsedBooking CloneSeed(ParsedBooking s) => new()
{
EmailUid = s.EmailUid,
MailboxScope = s.MailboxScope, ImapUid = s.ImapUid, UidValidity = s.UidValidity,
MessageId = s.MessageId, References = s.References, ReplyTo = s.ReplyTo,
IsAutomaticMessage = s.IsAutomaticMessage,
EmailSubject = s.EmailSubject,
EmailFrom = s.EmailFrom,
EmailDate = s.EmailDate,
EmailBody = s.EmailBody,
Status = RowStatus.New
};
private static void ApplyJsonToBooking(JsonElement root, ParsedBooking b)
{
b.Action = MapAction(GetStr(root, "action"));
var aiSubject = GetStr(root, "subject");
if (!string.IsNullOrWhiteSpace(aiSubject)) b.EmailSubject = aiSubject;
b.GuestFirstName = GetStr(root, "first_name");
b.GuestLastName = GetStr(root, "last_name");
b.Adults = GetInt(root, "adults", 1);
b.Children = GetInt(root, "children", 0);
b.OriginalCheckIn = GetDate(root, "original_checkin");
b.ArrivalDate = GetDate(root, "checkin");
b.Nights = Math.Max(1, GetInt(root, "nights", 1));
b.Rooms = Math.Max(1, GetInt(root, "rooms", 1));
if (b.ArrivalDate is DateTime a)
b.DepartureDate = a.AddDays(b.Nights);
b.RoomType = GetStr(root, "room_type");
b.RatePlanCode = GetStr(root, "rate_plan");
b.PackageCode = GetStr(root, "package_code");
b.Upsells = GetStr(root, "upsells");
b.PaymentGuarantee = GetStr(root, "payment_guarantee");
b.Comment = GetStr(root, "comment");
b.GuestEmail = GetStr(root, "email");
b.GuestPhone = GetStr(root, "phone");
b.NewEmail = GetStr(root, "new_email");
b.NewPhone = GetStr(root, "new_phone");
b.CancellationReason = GetStr(root, "cancellation_reason");
b.ConfirmationNumber = GetStr(root, "confirmation_number");
b.ReservationId = GetStr(root, "opera_res_id");
b.Confidence = Math.Clamp(GetInt(root, "confidence", 0), 0, 100);
b.AiRationale = GetStr(root, "rationale");
b.Status = b.Action == BookingAction.None ? RowStatus.LowConfidence : RowStatus.New;
}
private static string ExtractFirstJsonObject(string raw)
{
var text = raw.Trim();
if (text.StartsWith("```", StringComparison.Ordinal))
{
var newline = text.IndexOf('\n');
if (newline >= 0 && text.EndsWith("```", StringComparison.Ordinal))
text = text[(newline + 1)..^3].Trim();
}
return text; // JsonDocument handles braces and escapes inside strings correctly.
}
private static string GetStr(JsonElement e, string name) =>
e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
? v.GetString() ?? "" : "";
private static int GetInt(JsonElement e, string name, int def)
{
if (!e.TryGetProperty(name, out var v)) return def;
if (v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var n)) return n;
if (v.ValueKind == JsonValueKind.String && int.TryParse(v.GetString(), out var s)) return s;
return def;
}
private static DateTime? GetDate(JsonElement e, string name)
{
if (!e.TryGetProperty(name, out var v) || v.ValueKind != JsonValueKind.String) return null;
var s = v.GetString();
return DateTime.TryParse(s, out var d) ? d : (DateTime?)null;
}
private static BookingAction MapAction(string action) => action?.Trim().ToLowerInvariant() switch
{
"create" => BookingAction.CreateBooking,
"cancel" => BookingAction.CancelBooking,
"change_checkin" => BookingAction.ChangeCheckIn,
"change_room" => BookingAction.ChangeRoomType,
"change_rate" => BookingAction.ChangeRate,
"add_package" => BookingAction.AddPackage,
"remove_package" => BookingAction.RemovePackage,
"update_email" => BookingAction.UpdateEmail,
"update_phone" => BookingAction.UpdatePhone,
"update_comment" => BookingAction.UpdateComment,
"send_invoice" => BookingAction.SendInvoice,
"quote_request" => BookingAction.QuoteRequest,
"rate_quote" => BookingAction.QuoteRequest,
"quote" => BookingAction.QuoteRequest,
_ => BookingAction.None
};
}
/// <summary>Common contract for any LLM that turns one email seed into 1+ rows.</summary>
public interface IAiExtractor
{
System.Threading.Tasks.Task<List<ParsedBooking>> ExtractAllAsync(
ParsedBooking seed, System.Threading.CancellationToken ct = default);
}
+23
View File
@@ -0,0 +1,23 @@
using GuestOps.Models;
namespace GuestOps.Services;
public static class BookingValidation
{
public static bool IsCurrency(string? value) => value != null && value.Length == 3 && value.All(c => c is >= 'A' and <= 'Z' or >= 'a' and <= 'z');
public static string? Stay(ParsedBooking row)
{
if (row.Rooms != 1) return "Multi-room requests require staff handling; split into individually priced reservations before taking payment.";
if (!row.ArrivalDate.HasValue || !row.DepartureDate.HasValue || row.DepartureDate <= row.ArrivalDate || row.ArrivalDate.Value.Date < DateTime.Today)
return "A valid future arrival and later departure are required.";
if (row.Adults < 1 || row.Children < 0) return "Guest counts are invalid.";
return null;
}
public static string? Validate(ParsedBooking row)
{
if (row.IsAutomaticMessage) return "Automated/list/bounce messages are not eligible for processing.";
if (row.Action == BookingAction.None) return "Review or reparse this email; no supported action is selected.";
if (row.Action is BookingAction.CreateBooking or BookingAction.QuoteRequest) return Stay(row);
if (string.IsNullOrWhiteSpace(row.ConfirmationNumber)) return "A confirmation number is required.";
return null;
}
}
+73
View File
@@ -0,0 +1,73 @@
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace GuestOps.Services;
/// <summary>
/// Lightweight, dependency-free pre-cleanup of email bodies before they
/// are handed to the AI. Removes the bulk of HTML, common signature
/// blocks, forwarded-reply quotes, mail-client footers and excess
/// whitespace. Keeps the body readable for the AI without changing the
/// underlying meaning.
/// </summary>
public static class EmailBodyCleaner
{
private static readonly Regex HtmlTagRx = new(@"<[^>]+>", RegexOptions.Compiled | RegexOptions.Singleline);
private static readonly Regex HtmlEntityRx = new(@"&(nbsp|amp|lt|gt|quot|#\d+);", RegexOptions.Compiled);
private static readonly Regex StyleScriptRx = new(@"<(script|style)[^>]*>.*?</\1>", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase);
private static readonly Regex BlankLinesRx = new(@"(\r?\n){3,}", RegexOptions.Compiled);
private static readonly Regex QuoteHeaderRx = new(@"(?im)^(on .+ wrote:|from:\s.+|le .+ a écrit\s*:|am .+ schrieb:)$.*", RegexOptions.Compiled);
private static readonly Regex QuotedLineRx = new(@"(?m)^>.*$\r?\n?", RegexOptions.Compiled);
private static readonly Regex SignatureRx = new(
@"(?ms)\r?\n--\s*\r?\n.*$" +
@"|(?ms)\r?\n_{6,}\r?\n.*$" +
@"|(?ms)\r?\nsent from my (iphone|ipad|android|samsung).*$" +
@"|(?ms)\r?\n(get outlook for|this email and any attachments).*$",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
public static string Clean(string body)
{
if (string.IsNullOrWhiteSpace(body)) return "";
var s = body;
// 1. Strip <script>/<style> blocks then any remaining HTML tags.
if (s.Contains('<') && s.Contains('>'))
{
s = StyleScriptRx.Replace(s, " ");
s = HtmlTagRx.Replace(s, " ");
s = HtmlEntityRx.Replace(s, m => m.Groups[1].Value.ToLowerInvariant() switch
{
"nbsp" => " ",
"amp" => "&",
"lt" => "<",
"gt" => ">",
"quot" => "\"",
_ => ""
});
}
// 2. Drop forwarded-reply headers ("On X, Y wrote:") and the quoted lines that follow.
s = QuoteHeaderRx.Replace(s, "");
s = QuotedLineRx.Replace(s, "");
// 3. Strip standard signature blocks.
s = SignatureRx.Replace(s, "");
// 4. Whitespace tidy.
s = s.Replace("\r\n", "\n");
s = BlankLinesRx.Replace(s, "\n\n");
s = s.Trim();
return s;
}
/// <summary>Truncate over-long bodies so we don't blow the LLM context window.</summary>
public static string Truncate(string body, int maxChars)
{
if (body.Length <= maxChars) return body;
return body[..maxChars] + "\n\n[...truncated, " + (body.Length - maxChars) + " more chars...]";
}
}
+1
View File
@@ -0,0 +1 @@
<Project Sdk="Microsoft.NET.Sdk" />
+174
View File
@@ -0,0 +1,174 @@
using System;
using System.Collections.Generic;
namespace GuestOps.Models;
/// <summary>
/// Amendment actions extracted from an email by the AI, or selectable manually.
/// Mirrors the `actions/*.ps1` scripts in the PowerShell original.
/// </summary>
public enum BookingAction
{
None,
CreateBooking,
CancelBooking,
ChangeCheckIn,
ChangeRoomType,
ChangeRate,
AddPackage,
RemovePackage,
UpdateEmail,
UpdatePhone,
UpdateComment,
SendInvoice,
QuoteRequest
}
/// <summary>
/// The status of a parsed booking as shown in the grid (drives row color).
/// </summary>
public enum RowStatus
{
New,
Reviewed,
Processing,
Success,
Failed,
Skipped,
LowConfidence,
Simulated,
NeedsReview
}
/// <summary>
/// One parsed email -> one (or several) candidate actions against Opera.
/// Bound to the DataGridView.
/// </summary>
public class ParsedBooking
{
public string ActionId { get; set; } = Guid.NewGuid().ToString("N");
public bool ExtractionComplete { get; set; }
public int ExtractionAttempts { get; set; }
public bool NotificationsComplete { get; set; }
public string MailboxScope { get; set; } = "";
public uint ImapUid { get; set; }
public uint UidValidity { get; set; }
public string MessageId { get; set; } = "";
public string ReplyTo { get; set; } = "";
public string References { get; set; } = "";
public bool IsAutomaticMessage { get; set; }
public string QuoteId { get; set; } = "";
public string Currency { get; set; } = "";
// Grid / selection
public bool Selected { get; set; } = false;
public RowStatus Status { get; set; } = RowStatus.New;
public string StatusMessage{ get; set; } = "";
// Source email ---------------------------------------------------------
public string EmailUid { get; set; } = "";
public string EmailSubject { get; set; } = "";
public string EmailFrom { get; set; } = "";
public DateTime EmailDate { get; set; } = DateTime.MinValue;
public string EmailBody { get; set; } = "";
// AI extraction --------------------------------------------------------
public BookingAction Action { get; set; } = BookingAction.None;
public int Confidence { get; set; } = 0;
public string AiRationale { get; set; } = "";
// Opera identifiers ----------------------------------------------------
public string ConfirmationNumber { get; set; } = "";
public string ReservationId { get; set; } = ""; // OHIP resvId
public string ProfileId { get; set; } = "";
// Guest ----------------------------------------------------------------
public string GuestFirstName { get; set; } = "";
public string GuestLastName { get; set; } = "";
public string GuestEmail { get; set; } = "";
public string GuestPhone { get; set; } = "";
/// <summary>
/// Short loyalty badge string ("ALL/GOLD", "WYNDHAM/PLATINUM", etc.)
/// populated from a matched OHIP profile's memberships. Rendered as
/// the "Loyalty" column so operators can spot member stays at a glance.
/// Empty for non-member or unmatched guests.
/// </summary>
public string LoyaltyBadge { get; set; } = "";
// Stay -----------------------------------------------------------------
public DateTime? ArrivalDate { get; set; }
public DateTime? DepartureDate { get; set; }
public DateTime? OriginalCheckIn { get; set; } // for change-checkin actions
public int Nights { get; set; } = 1;
public int Rooms { get; set; } = 1;
public string RoomType { get; set; } = "";
public string RatePlanCode { get; set; } = "";
public decimal? RateAmount { get; set; }
public int Adults { get; set; } = 1;
public int Children { get; set; } = 0;
public string PackageCode { get; set; } = "";
public string Upsells { get; set; } = "";
public string PaymentGuarantee { get; set; } = "";
public string CancellationReason { get; set; } = "";
// Free-form
public string NewEmail { get; set; } = "";
public string NewPhone { get; set; } = "";
public string Comment { get; set; } = "";
public string ActionLabel => Action switch
{
BookingAction.CreateBooking => "Create",
BookingAction.CancelBooking => "Cancel",
BookingAction.ChangeCheckIn => "Change Check-in",
BookingAction.ChangeRoomType => "Change Room",
BookingAction.ChangeRate => "Change Rate",
BookingAction.AddPackage => "Add Package",
BookingAction.RemovePackage => "Remove Package",
BookingAction.UpdateEmail => "Update Email",
BookingAction.UpdatePhone => "Update Phone",
BookingAction.UpdateComment => "Update Comment",
BookingAction.SendInvoice => "Send Invoice",
BookingAction.QuoteRequest => "Send Quote",
_ => "(none)"
};
}
/// <summary>
/// Reservation snapshot returned from Opera (SOAP or REST).
/// </summary>
public class ReservationInfo
{
public string ConfirmationNumber { get; set; } = "";
public string ReservationId { get; set; } = "";
public string ProfileId { get; set; } = "";
public string Status { get; set; } = ""; // RESERVED / CHECKEDIN / CHECKEDOUT / CANCELED
public DateTime? ArrivalDate { get; set; }
public DateTime? DepartureDate { get; set; }
public string RoomType { get; set; } = "";
public string RatePlanCode { get; set; } = "";
public decimal? RateAmount { get; set; }
public string GuestFirstName { get; set; } = "";
public string GuestLastName { get; set; } = "";
public string PrimaryEmail { get; set; } = "";
public string PrimaryPhone { get; set; } = "";
public List<string> Packages { get; set; } = new();
public string RawPayload { get; set; } = ""; // for diagnostics
}
/// <summary>
/// Generic result of a dispatcher call.
/// </summary>
public class OperaResult
{
public bool Success { get; set; }
public bool IsSimulation { get; set; }
public bool RequiresReview { get; set; }
public static OperaResult Simulated(string message) => new() { IsSimulation = true, Message = message };
public static OperaResult Review(string message) => new() { RequiresReview = true, Message = message };
public string Message { get; set; } = "";
public string RawResponse { get; set; } = "";
public static OperaResult Ok(string msg, string raw = "") => new() { Success = true, Message = msg, RawResponse = raw };
public static OperaResult Fail(string msg, string raw = "") => new() { Success = false, Message = msg, RawResponse = raw };
}
+17
View File
@@ -0,0 +1,17 @@
using System.Text.RegularExpressions;
namespace GuestOps.Services;
public static class SecretRedactor
{
private const string Keys = "access_token|refresh_token|id_token|client_secret|password|UserPassword|security_key|NmiSecurityKey|PlanetApiKey|OpenAiApiKey|OhipClientSecret|OhipAppKey|OwsPassword|ImapPassword|SmtpPassword|OhipPassword|HotelKeyPrivateKeyPem";
public static string Redact(string? value)
{
var text = value ?? "";
text = Regex.Replace(text, "(\"(?:" + Keys + ")\"\\s*:\\s*)\"(?:\\\\.|[^\"\\\\])*\"", "$1\"[REDACTED]\"", RegexOptions.IgnoreCase);
text = Regex.Replace(text, "(<(?:\\w+:)?(?:" + Keys + ")(?:\\s[^>]*)?>)[\\s\\S]*?(</(?:\\w+:)?(?:" + Keys + ")>)", "$1[REDACTED]$2", RegexOptions.IgnoreCase);
text = Regex.Replace(text, @"(?im)^(Authorization\s*:\s*).*$", "$1[REDACTED]");
text = Regex.Replace(text, @"-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----", "[REDACTED PRIVATE KEY]");
return text;
}
}
@@ -0,0 +1 @@
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType></PropertyGroup><ItemGroup><FrameworkReference Include="Microsoft.AspNetCore.App"/><ProjectReference Include="../GuestOps.Api/GuestOps.Api.csproj"/></ItemGroup></Project>
+48
View File
@@ -0,0 +1,48 @@
using GuestOps.Web;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.ClearProviders(); builder.Logging.AddConsole();
builder.Logging.AddFilter("System.Net.Http.HttpClient", LogLevel.Warning);
builder.Services.AddSingleton<IStore, MongoStore>();
var keyPath = builder.Configuration["Keys:Path"] ?? throw new InvalidOperationException("Keys:Path is required.");
builder.Services.AddDataProtection().SetApplicationName("GuestOps-Web").PersistKeysToFileSystem(new DirectoryInfo(keyPath));
builder.Services.AddHttpClient<GoogleMailbox>(c => c.Timeout = TimeSpan.FromSeconds(25));
builder.Services.AddHostedService<MailboxWorker>();
await builder.Build().RunAsync();
sealed class MailboxWorker(IStore store, IServiceScopeFactory factory, ILogger<MailboxWorker> log) : BackgroundService
{
readonly string owner = Guid.NewGuid().ToString("N");
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await store.Initialize();
while (!stoppingToken.IsCancellationRequested)
{
try
{
foreach (var mailbox in await store.Mailboxes())
{
if (!await store.TryLease(mailbox.Id, owner)) continue;
// Per-page deadline is shorter than the lease. Import is idempotent.
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); deadline.CancelAfter(TimeSpan.FromMinutes(2));
try { using var scope = factory.CreateScope(); await scope.ServiceProvider.GetRequiredService<GoogleMailbox>().Sync(mailbox, deadline.Token); }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
catch (Exception ex)
{
log.LogWarning("Mailbox synchronization paused for {Id} ({Type})", mailbox.Id, ex.GetType().Name);
mailbox.SyncError = "Synchronization failed. Retry later or reconnect your Google mailbox.";
await store.SaveSync(mailbox);
}
finally { await store.ReleaseLease(mailbox.Id, owner); }
}
}
catch (Exception ex) when (!stoppingToken.IsCancellationRequested) { log.LogWarning("Worker cycle paused ({Type})", ex.GetType().Name); }
await Task.Delay(TimeSpan.FromSeconds(60), stoppingToken);
}
}
}