Add reviewed AI drafts and durable staff-approved Gmail delivery
This commit is contained in:
@@ -25,7 +25,8 @@ if (!preview && string.IsNullOrWhiteSpace(keyPath)) throw new InvalidOperationEx
|
||||
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.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.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
|
||||
{
|
||||
o.Cookie.Name = "guestops.session"; o.Cookie.HttpOnly = true; o.Cookie.SameSite = SameSiteMode.Lax;
|
||||
@@ -54,6 +55,7 @@ builder.Services.AddAntiforgery(o => { o.HeaderName = "X-CSRF-TOKEN"; o.Cookie.N
|
||||
builder.Services.AddRateLimiter(o =>
|
||||
{
|
||||
o.RejectionStatusCode = 429;
|
||||
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 }));
|
||||
});
|
||||
var app = builder.Build();
|
||||
@@ -125,10 +127,12 @@ api.MapPut("/hotel", async (SettingsInput input, HttpContext c) =>
|
||||
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.MapGet("/conversations/{id}", async (string id, HttpContext c) => await store.Get<Conversation>(Session.Hotel(c), id) is { } item ? Results.Ok(item) : Results.NotFound());
|
||||
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();
|
||||
if (item.Delivery != null) return Results.Conflict(new { error = "This reply has already been approved for delivery. Its text is locked." });
|
||||
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);
|
||||
@@ -137,6 +141,7 @@ api.MapPut("/conversations/{id}/status", async (string id, StatusInput input, Ht
|
||||
{
|
||||
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();
|
||||
if (item.Delivery != null && item.Delivery.State != "Sent") return Results.Conflict(new { error = "Resolve the pending delivery before changing this conversation." });
|
||||
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);
|
||||
@@ -157,7 +162,68 @@ api.MapPut("/knowledge/{id}", async (string id, KnowledgeInput input, HttpContex
|
||||
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.MapGet("/mailboxes", async (HttpContext c, GoogleMailbox google, AiDrafts ai) => Results.Ok(new { configured = !preview && google.Configured, sendingConfigured = !preview && google.SendingConfigured, aiConfigured = !preview && ai.Configured, items = (await store.List<Mailbox>(Session.Hotel(c))).Select(x => new { x.Id, x.Email, x.Status, x.LastSyncAt, x.SyncError, x.CanSend }) }));
|
||||
api.MapPut("/reply-controls", async (ReplyControlsInput input, HttpContext c, GoogleMailbox google, AiDrafts ai) =>
|
||||
{
|
||||
if ((input.AiDraftsEnabled && (preview || !ai.Configured)) || (input.StaffSendingEnabled && (preview || !google.SendingConfigured))) return Results.BadRequest(new { error = "The administrator must configure this capability first." });
|
||||
var hotel = await store.Get<Hotel>(Session.Hotel(c), Session.Hotel(c)); if (hotel == null) return Results.NotFound();
|
||||
hotel.AiDraftsEnabled = input.AiDraftsEnabled; hotel.StaffSendingEnabled = input.StaffSendingEnabled; hotel.ReplyMode = input.StaffSendingEnabled ? "StaffApproved" : "DraftOnly"; 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 AI and staff sending controls"); return Results.Ok(hotel);
|
||||
}).RequireAuthorization("Owner");
|
||||
api.MapPost("/conversations/{id}/generate", async (string id, VersionInput input, HttpContext c, AiDrafts ai) =>
|
||||
{
|
||||
var item = await store.Get<Conversation>(Session.Hotel(c), id); if (item == null) return Results.NotFound();
|
||||
var hotel = await store.Get<Hotel>(item.HotelId, item.HotelId);
|
||||
if (preview || !ai.Configured || hotel?.AiDraftsEnabled != true) return Results.BadRequest(new { error = "AI drafts are not enabled for this hotel." });
|
||||
if (item.Version != input.Version || item.Delivery != null) return Input.Conflict();
|
||||
var sources = AiDrafts.SelectSources(item, await store.List<KnowledgeEntry>(item.HotelId));
|
||||
var result = await ai.Generate(item, sources, c.RequestAborted);
|
||||
// A knowledge edit during generation invalidates the result before it is saved.
|
||||
foreach (var source in sources)
|
||||
{
|
||||
var current = await store.Get<KnowledgeEntry>(item.HotelId, source.Id);
|
||||
if (current?.Approved != true || current.Version != source.Version) return Input.Conflict();
|
||||
}
|
||||
item.Draft = result.Draft.Length > 0 ? result.Draft + "\n\n" + hotel.Signature : "";
|
||||
item.DraftSources = result.SourceIds; item.DraftReviewNote = result.Reason;
|
||||
item.Status = result.NeedsReview ? "NeedsAttention" : "DraftReady"; item.Version++;
|
||||
if (!await store.Replace(item.HotelId, item.Id, input.Version, item)) return Input.Conflict();
|
||||
await Session.Audit(store, c, result.NeedsReview ? "AI requested staff handling" : "Generated a draft for staff review"); return Results.Ok(item);
|
||||
}).RequireRateLimiting("ai");
|
||||
api.MapPost("/conversations/{id}/send", async (string id, SendInput input, HttpContext c, GoogleMailbox google) =>
|
||||
{
|
||||
var item = await store.Get<Conversation>(Session.Hotel(c), id); if (item == null) return Results.NotFound();
|
||||
if (item.Delivery != null) return Results.Conflict(new { error = "This message already has a delivery request. Refresh to see its status." });
|
||||
var hotel = await store.Get<Hotel>(item.HotelId, item.HotelId); var mailbox = await store.Get<Mailbox>(item.HotelId, item.MailboxId);
|
||||
if (preview || hotel?.StaffSendingEnabled != true || !google.SendingConfigured || mailbox?.CanSend != true) return Results.BadRequest(new { error = "Enable staff sending and reconnect Google with send permission first." });
|
||||
if (item.Version != input.Version) return Input.Conflict();
|
||||
if (input.Recipient != item.ReplyAddress || string.IsNullOrWhiteSpace(item.ReplyAddress)) return Results.BadRequest(new { error = "The recipient must match the message's reply address." });
|
||||
item.Delivery = new Delivery { Recipient = item.ReplyAddress, Body = item.Draft, ApprovedBy = c.User.FindFirstValue(ClaimTypes.NameIdentifier)! };
|
||||
try { _ = ReplyMime.Build(item, mailbox); } catch { return Results.BadRequest(new { error = "This message lacks valid reply metadata or a saved draft. Reply in Gmail instead." }); }
|
||||
item.Version++;
|
||||
if (!await store.Replace(item.HotelId, item.Id, input.Version, item)) return Input.Conflict();
|
||||
await Session.Audit(store, c, "Approved a saved reply for Gmail delivery"); return Results.Ok(item);
|
||||
});
|
||||
api.MapPost("/conversations/{id}/delivery/retry", async (string id, VersionInput input, HttpContext c) =>
|
||||
{
|
||||
var item = await store.Get<Conversation>(Session.Hotel(c), id); if (item == null) return Results.NotFound();
|
||||
if (preview || item.Delivery?.State != "Rejected" || item.Version != input.Version) return Input.Conflict();
|
||||
item.Delivery.State = "Pending"; item.Delivery.UpdatedAt = DateTime.UtcNow; item.Version++;
|
||||
if (!await store.Replace(item.HotelId, item.Id, input.Version, item)) return Input.Conflict();
|
||||
await Session.Audit(store, c, "Retried a reply that had not reached Gmail sending"); return Results.Ok(item);
|
||||
});
|
||||
api.MapPost("/conversations/{id}/delivery/verify", async (string id, VersionInput input, HttpContext c, GoogleMailbox google) =>
|
||||
{
|
||||
var item = await store.Get<Conversation>(Session.Hotel(c), id); if (item == null) return Results.NotFound();
|
||||
if (preview || item.Delivery?.State != "NeedsReview" || item.Version != input.Version) return Input.Conflict();
|
||||
var mailbox = await store.Get<Mailbox>(item.HotelId, item.MailboxId); if (mailbox == null) return Results.BadRequest();
|
||||
var found = await google.FindSent(item, mailbox, c.RequestAborted);
|
||||
if (found == null) return Results.Conflict(new { error = "No unique matching sent message was found. Delivery remains uncertain; check Gmail manually. No resend was queued." });
|
||||
item.Delivery.ProviderId = found; item.Delivery.State = "Sent"; item.Delivery.Detail = "Verified in Gmail Sent"; item.Delivery.UpdatedAt = DateTime.UtcNow; item.Status = "Completed"; item.Version++;
|
||||
if (!await store.Replace(item.HotelId, item.Id, input.Version, item)) return Input.Conflict();
|
||||
await Session.Audit(store, c, "Verified uncertain delivery in Gmail Sent"); return Results.Ok(item);
|
||||
});
|
||||
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." });
|
||||
@@ -195,3 +261,4 @@ namespace GuestOps.Web
|
||||
public static IResult Conflict() => Results.Conflict(new { error = "Someone changed this record. Reload it before saving again." });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user