Add controlled FAQ auto-replies with test mode and durable sending limits
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
using System.Text.RegularExpressions;
|
||||
namespace GuestOps.Web;
|
||||
public sealed class AutoReplyRule:TenantDocument
|
||||
{
|
||||
public string Question {get;set;}="";
|
||||
public string KnowledgeId {get;set;}="";
|
||||
public long KnowledgeVersion {get;set;}
|
||||
public bool Enabled {get;set;}
|
||||
public long Version {get;set;}
|
||||
public string ApprovedBy {get;set;}="";
|
||||
}
|
||||
public sealed class AutoReplyClaim:TenantDocument
|
||||
{
|
||||
public string ThreadKey {get;set;}="";
|
||||
public string RecipientDay {get;set;}="";
|
||||
public string DaySlot {get;set;}="";
|
||||
public string ConversationId {get;set;}="";
|
||||
}
|
||||
public sealed record AutoRuleInput(string Question,string KnowledgeId,bool Enabled,long Version);
|
||||
public sealed record AutoModeInput(string Mode,long Version,bool AcceptanceConfirmed);
|
||||
public sealed record AutoTestInput(string Subject,string Body);
|
||||
public sealed record AutoDecision(bool Matches,string Reason,string RuleId="",string KnowledgeId="",string Body="");
|
||||
public static class FaqMatcher
|
||||
{
|
||||
public static readonly string[] Questions=["What time is check in?","What time is check out?","Where can I park?","Is parking available?","What time is breakfast?","Do you have WiFi?","What is your address?"];
|
||||
public static string Normalize(string value)=>Regex.Replace((value??"").Trim().ToLowerInvariant(),@"\s+"," ").TrimEnd('?','.');
|
||||
public static bool SubjectAllowed(string subject)=>new[]{"", "question", "quick question", "parking", "parking question", "check in", "check-in", "check out", "check-out", "breakfast", "wifi", "wi-fi", "address"}.Contains(Normalize(subject))||Questions.Any(q=>Normalize(q)==Normalize(subject));
|
||||
public static bool Sensitive(string text)=>Regex.IsMatch(text,@"\b(cancel\w*|refund\w*|pay\w*|card\w*|allerg\w*|medical|emergency|injur\w*|complain\w*|charge\w*|chang\w*|disab\w*|accessible|safety|fire|police|lost|stolen|urgent|booking|reservation)\b",RegexOptions.IgnoreCase);
|
||||
public static AutoDecision Evaluate(Conversation message,IEnumerable<AutoReplyRule> rules,IEnumerable<KnowledgeEntry> knowledge)
|
||||
{
|
||||
if(message.Body.Length>200||!SubjectAllowed(message.Subject)||Sensitive(message.Subject+" "+message.Body))return new(false,"This message needs staff handling.");
|
||||
var question=Normalize(message.Body);
|
||||
if(!Questions.Any(q=>Normalize(q)==question))return new(false,"The complete message does not match a supported FAQ question.");
|
||||
var matches=rules.Where(r=>r.HotelId==message.HotelId&&r.Enabled&&Normalize(r.Question)==question).ToArray();
|
||||
if(matches.Length!=1)return new(false,"Exactly one enabled rule is required.");
|
||||
var rule=matches[0];var answer=knowledge.SingleOrDefault(k=>k.Id==rule.KnowledgeId&&k.HotelId==message.HotelId);
|
||||
if(answer?.Approved!=true||answer.Version!=rule.KnowledgeVersion||string.IsNullOrWhiteSpace(answer.Answer))return new(false,"The approved answer changed or is unavailable. Review the rule again.");
|
||||
return new(true,"Exact FAQ match; the approved answer is used without AI rewriting.",rule.Id,answer.Id,answer.Answer);
|
||||
}
|
||||
public static bool HeadersEligible(System.Text.Json.JsonElement payload,string mailboxEmail)
|
||||
{
|
||||
if(!payload.TryGetProperty("headers",out var headers))return false;
|
||||
string[] Values(string name)=>headers.EnumerateArray().Where(h=>h.GetProperty("name").GetString()!.Equals(name,StringComparison.OrdinalIgnoreCase)).Select(h=>h.GetProperty("value").GetString()??"").ToArray();
|
||||
string One(string name)=>Values(name) is var values&&values.Length==1?values[0]:"";
|
||||
bool Absent(string name)=>Values(name).Length==0;
|
||||
bool Attachment(System.Text.Json.JsonElement p)=>p.TryGetProperty("filename",out var f)&&f.GetString()?.Length>0||p.TryGetProperty("body",out var body)&&body.TryGetProperty("attachmentId",out _)||p.TryGetProperty("parts",out var parts)&&parts.EnumerateArray().Any(Attachment);
|
||||
var from=ReplyMime.Address(One("From"));var reply=One("Reply-To");
|
||||
return payload.TryGetProperty("mimeType",out var mime)&&mime.GetString()=="text/plain"&&from.Length>0&&from!=mailboxEmail&&ReplyMime.Address(One("To"))==mailboxEmail&&Absent("Cc")&&Absent("Bcc")&&Absent("In-Reply-To")&&Absent("References")&&Absent("List-Id")&&Absent("Precedence")&&Absent("X-Auto-Response-Suppress")&&(Absent("Auto-Submitted")||One("Auto-Submitted").Equals("no",StringComparison.OrdinalIgnoreCase))&&(Absent("Reply-To")||ReplyMime.Address(reply)==from)&&One("Return-Path").Trim()!="<>"&&!Attachment(payload)&&!Regex.IsMatch(from,@"(^|[._-])(no.?reply|mailer.?daemon|postmaster)([.@_-]|$)",RegexOptions.IgnoreCase);
|
||||
}
|
||||
}
|
||||
public sealed class AutoReplyWork(IStore store,IConfiguration config)
|
||||
{
|
||||
public bool LiveConfigured=>config.GetValue<bool>("AutoReply:EnableLive");
|
||||
public async Task<AutoDecision> Test(string hotel,string subject,string body)=>FaqMatcher.Evaluate(new Conversation{HotelId=hotel,Subject=subject,Body=body},await store.List<AutoReplyRule>(hotel),await store.List<KnowledgeEntry>(hotel));
|
||||
public async Task Process(Conversation message)
|
||||
{
|
||||
var hotel=await store.Get<Hotel>(message.HotelId,message.HotelId);
|
||||
if(hotel==null||hotel.AutoReplyMode=="Off"||message.AutoReplyCheckedAt!=null)return;
|
||||
var box=await store.Get<Mailbox>(message.HotelId,message.MailboxId);
|
||||
AutoDecision result;
|
||||
if(!message.AutoReplyHeadersEligible||box?.Status!="Connected"||message.Delivery!=null||message.Version!=0||message.Status!="NeedsAttention"||message.Draft.Length>0||message.ReceivedAt<hotel.AutoReplySince||message.ReceivedAt<DateTime.UtcNow.AddHours(-24)||message.ReceivedAt>DateTime.UtcNow.AddMinutes(5))result=new(false,"Message metadata, age or existing staff work requires manual handling.");
|
||||
else result=await Test(message.HotelId,message.Subject,message.Body);
|
||||
var version=message.Version;message.AutoReplyCheckedAt=DateTime.UtcNow;message.AutoReplyDetail=result.Reason;message.AutoReplyMatched=result.Matches;
|
||||
message.Version++;if(!await store.Replace(message.HotelId,message.Id,version,message))return;version=message.Version;
|
||||
if(result.Matches&&hotel.AutoReplyMode=="Live")
|
||||
{
|
||||
if(!LiveConfigured||!hotel.StaffSendingEnabled||box?.CanSend!=true){message.AutoReplyDetail="Automatic sending is disabled by server or mailbox controls.";}
|
||||
else
|
||||
{
|
||||
var rule=(await store.Get<AutoReplyRule>(message.HotelId,result.RuleId))!;
|
||||
message.Delivery=new Delivery{Automatic=true,AutoDay=DateTime.UtcNow.ToString("yyyy-MM-dd"),AutoRuleId=rule.Id,AutoRuleVersion=rule.Version,AutoKnowledgeId=rule.KnowledgeId,AutoKnowledgeVersion=rule.KnowledgeVersion,AutoEpoch=hotel.AutoReplyEpoch,Recipient=message.ReplyAddress,Body=result.Body+"\n\n"+hotel.Signature,ApprovedBy=rule.ApprovedBy};
|
||||
bool valid=await CanDeliver(store,config,message);
|
||||
try{_=ReplyMime.Build(message,box!);}catch{valid=false;}
|
||||
if(valid&&await Claim(message)){message.Draft=message.Delivery.Body;message.DraftSources=[result.KnowledgeId];message.AutoReplyDetail="Queued the approved FAQ answer for automatic delivery.";}
|
||||
else{message.Delivery=null;message.AutoReplyDetail="Automatic reply was held by current controls, a changed rule, or delivery limits.";}
|
||||
}
|
||||
}
|
||||
else if(result.Matches)message.AutoReplyDetail="Test match only: "+result.Reason;
|
||||
message.Version++;await store.Replace(message.HotelId,message.Id,version,message);
|
||||
}
|
||||
public async Task<bool> ReturnToStaff(Conversation message,long version)
|
||||
{
|
||||
if(message.Version!=version||message.Delivery?.Automatic!=true||message.Delivery.State!="Rejected")return false;
|
||||
message.RejectedAutomaticReply=message.Delivery;message.Delivery=null;message.Status="DraftReady";message.AutoReplyDetail="Automatic reply stopped before submission and returned to staff review.";message.Version++;
|
||||
return await store.Replace(message.HotelId,message.Id,version,message);
|
||||
}
|
||||
async Task<bool> Claim(Conversation message)
|
||||
{
|
||||
if(message.ReplyAddress.Length==0||message.ProviderThreadId.Length==0)return false;
|
||||
var day=message.Delivery!.AutoDay;
|
||||
for(int slot=0;slot<20;slot++)if(await store.TryAutoReplyClaim(new AutoReplyClaim{HotelId=message.HotelId,ThreadKey=message.MailboxId+":"+message.ProviderThreadId,RecipientDay=day+":"+message.ReplyAddress,DaySlot=day+":"+slot,ConversationId=message.Id}))return true;
|
||||
return false;
|
||||
}
|
||||
public static async Task<bool> CanDeliver(IStore store,IConfiguration? config,Conversation message)
|
||||
{
|
||||
var d=message.Delivery;if(d?.Automatic!=true)return true;
|
||||
if(config?.GetValue<bool>("AutoReply:EnableLive")!=true)return false;
|
||||
var hotel=await store.Get<Hotel>(message.HotelId,message.HotelId);var rule=await store.Get<AutoReplyRule>(message.HotelId,d.AutoRuleId);var answer=await store.Get<KnowledgeEntry>(message.HotelId,d.AutoKnowledgeId);
|
||||
return d.AutoDay==DateTime.UtcNow.ToString("yyyy-MM-dd")&&hotel?.AutoReplyMode=="Live"&&hotel.AutoReplyEpoch==d.AutoEpoch&&hotel.StaffSendingEnabled&&rule?.Enabled==true&&rule.Version==d.AutoRuleVersion&&FaqMatcher.Normalize(rule.Question)==FaqMatcher.Normalize(message.Body)&&FaqMatcher.SubjectAllowed(message.Subject)&&!FaqMatcher.Sensitive(message.Subject+" "+message.Body)&&rule.KnowledgeId==d.AutoKnowledgeId&&rule.KnowledgeVersion==d.AutoKnowledgeVersion&&answer?.Approved==true&&answer.Version==d.AutoKnowledgeVersion&&d.Body==answer.Answer+"\n\n"+hotel.Signature&&message.AutoReplyHeadersEligible&&message.ReceivedAt>=hotel.AutoReplySince&&message.ReceivedAt>=DateTime.UtcNow.AddHours(-24);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using MongoDB.Driver;
|
||||
namespace GuestOps.Web;
|
||||
public static class AutoReplyEndpoints
|
||||
{
|
||||
public static void Map(RouteGroupBuilder api,bool preview)
|
||||
{
|
||||
var group=api.MapGroup("/auto-replies").RequireRateLimiting("pms");
|
||||
group.MapGet("/status",(AutoReplyWork work)=>Results.Ok(new{liveConfigured=!preview&&work.LiveConfigured,preview,questions=FaqMatcher.Questions,dailyLimit=20}));
|
||||
group.MapGet("/rules",async(HttpContext c,IStore store)=>Results.Ok(await store.List<AutoReplyRule>(Session.Hotel(c))));
|
||||
group.MapGet("/history",async(HttpContext c,IStore store)=>Results.Ok((await store.List<Conversation>(Session.Hotel(c))).Where(m=>m.AutoReplyCheckedAt!=null).OrderByDescending(m=>m.AutoReplyCheckedAt).Select(m=>new{m.Id,m.Subject,m.From,m.AutoReplyCheckedAt,m.AutoReplyMatched,m.AutoReplyDetail,delivery=m.Delivery?.State})));
|
||||
group.MapPost("/test",async(AutoTestInput input,HttpContext c,AutoReplyWork work)=>{
|
||||
if(!Input.Text(input.Subject,0,200)||!Input.Text(input.Body,1,2000))return Results.BadRequest();return Results.Ok(await work.Test(Session.Hotel(c),input.Subject,input.Body));
|
||||
}).RequireAuthorization("Owner");
|
||||
group.MapPut("/rules/{question:int}",async(int question,AutoRuleInput input,HttpContext c,IStore store)=>{
|
||||
if(question<0||question>=FaqMatcher.Questions.Length||input.Question!=FaqMatcher.Questions[question])return Results.BadRequest();
|
||||
var hotel=Session.Hotel(c);var key=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(hotel+":"+question))).ToLowerInvariant()[..32];
|
||||
var answer=await store.Get<KnowledgeEntry>(hotel,input.KnowledgeId);if(answer?.Approved!=true)return Results.BadRequest(new{error="Choose an approved answer from this hotel."});
|
||||
var rule=await store.Get<AutoReplyRule>(hotel,key);bool exists=rule!=null;
|
||||
if(!exists&&input.Version!=0)return Input.Conflict();
|
||||
rule??=new AutoReplyRule{Id=key,HotelId=hotel};rule.Question=input.Question;rule.KnowledgeId=answer.Id;rule.KnowledgeVersion=answer.Version;rule.Enabled=input.Enabled;rule.ApprovedBy=c.User.FindFirstValue(ClaimTypes.NameIdentifier)!;rule.Version=input.Version+1;
|
||||
if(exists){if(!await store.Replace(hotel,key,input.Version,rule))return Input.Conflict();}
|
||||
else{try{await store.Insert(rule);}catch(MongoWriteException ex) when(ex.WriteError.Category==ServerErrorCategory.DuplicateKey){return Input.Conflict();}}
|
||||
await Session.Audit(store,c,"Reviewed FAQ automatic reply rule: "+rule.Question);return Results.Ok(rule);
|
||||
}).RequireAuthorization("Owner");
|
||||
group.MapPut("/mode",async(AutoModeInput input,HttpContext c,IStore store,AutoReplyWork work,GoogleMailbox google)=>{
|
||||
if(input.Mode is not ("Off" or "Test" or "Live"))return Results.BadRequest();
|
||||
var hotel=await store.Get<Hotel>(Session.Hotel(c),Session.Hotel(c));if(hotel==null)return Results.NotFound();
|
||||
if(input.Mode=="Live"&&(preview||!work.LiveConfigured||!google.SendingConfigured||!hotel.StaffSendingEnabled||!input.AcceptanceConfirmed))return Results.BadRequest(new{error="Live mode requires administrator enablement, Google sending, hotel sending and confirmed test-mode acceptance."});
|
||||
hotel.AutoReplyMode=input.Mode;hotel.AutoReplyEpoch=Guid.NewGuid().ToString("N");hotel.AutoReplySince=DateTime.UtcNow;hotel.Version=input.Version+1;
|
||||
if(!await store.Replace(hotel.HotelId,hotel.Id,input.Version,hotel))return Input.Conflict();await Session.Audit(store,c,"Set FAQ automation mode: "+input.Mode);return Results.Ok(hotel);
|
||||
}).RequireAuthorization("Owner");
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,7 @@ public sealed class GoogleMailbox(HttpClient http, IConfiguration config, IStore
|
||||
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 };
|
||||
row.ReplyAddress = ReplyMime.Address(Header("Reply-To").Length > 0 ? Header("Reply-To") : Header("From"));
|
||||
row.RfcMessageId = Header("Message-ID");
|
||||
row.AutoReplyHeadersEligible = FaqMatcher.HeadersEligible(payload,mailbox.Email);
|
||||
await store.Import(row); // deduplicated before advancing the page checkpoint
|
||||
}
|
||||
mailbox.PageToken = page.TryGetProperty("nextPageToken", out var next) ? next.GetString()! : "";
|
||||
@@ -85,6 +86,12 @@ public sealed class GoogleMailbox(HttpClient http, IConfiguration config, IStore
|
||||
var token = await Token(new() { ["refresh_token"] = protector.Unprotect(mailbox.ProtectedRefreshToken), ["grant_type"] = "refresh_token" }, ct);
|
||||
return token.GetProperty("access_token").GetString()!;
|
||||
}
|
||||
public async Task<bool> AutoReplyThreadUnchanged(Conversation message,string token,CancellationToken ct)
|
||||
{
|
||||
var thread=await Read("threads/"+Uri.EscapeDataString(message.ProviderThreadId)+"?format=metadata",token,ct);
|
||||
if(!thread.TryGetProperty("messages",out var messages)||messages.GetArrayLength()!=1)return false;
|
||||
var only=messages[0];return only.GetProperty("id").GetString()==message.ProviderMessageId&&only.TryGetProperty("labelIds",out var labels)&&labels.EnumerateArray().Any(x=>x.GetString()=="INBOX")&&!labels.EnumerateArray().Any(x=>x.GetString()=="SENT");
|
||||
}
|
||||
public async Task<string> Send(Conversation message, string token, string raw, CancellationToken ct)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "https://gmail.googleapis.com/gmail/v1/users/me/messages/send") { Content = JsonContent.Create(new { raw, threadId = message.ProviderThreadId }) };
|
||||
|
||||
@@ -9,6 +9,9 @@ public abstract class TenantDocument : ITenantDocument
|
||||
}
|
||||
public class Hotel : TenantDocument
|
||||
{
|
||||
public string AutoReplyMode {get;set;}="Off";
|
||||
public string AutoReplyEpoch {get;set;}="";
|
||||
public DateTime AutoReplySince {get;set;}=DateTime.UtcNow;
|
||||
public bool PaymentsEnabled { get; set; }
|
||||
public bool PmsUpdatesEnabled { get; set; }
|
||||
public bool AiDraftsEnabled { get; set; }
|
||||
@@ -38,10 +41,15 @@ public class KnowledgeEntry : TenantDocument
|
||||
}
|
||||
public class Conversation : TenantDocument
|
||||
{
|
||||
public bool AutoReplyHeadersEligible {get;set;}
|
||||
public DateTime? AutoReplyCheckedAt {get;set;}
|
||||
public string AutoReplyDetail {get;set;}="";
|
||||
public bool AutoReplyMatched {get;set;}
|
||||
public string ReplyAddress { get; set; } = "";
|
||||
public string RfcMessageId { get; set; } = "";
|
||||
public string[] DraftSources { get; set; } = [];
|
||||
public string DraftReviewNote { get; set; } = "";
|
||||
public Delivery? RejectedAutomaticReply {get;set;}
|
||||
public Delivery? Delivery { get; set; }
|
||||
public string MailboxId { get; set; } = "";
|
||||
public string ProviderMessageId { get; set; } = "";
|
||||
@@ -95,6 +103,13 @@ public record SendInput(long Version, string Recipient);
|
||||
public record ReplyControlsInput(long Version, bool AiDraftsEnabled, bool StaffSendingEnabled);
|
||||
public class Delivery
|
||||
{
|
||||
public bool Automatic {get;set;}
|
||||
public string AutoRuleId {get;set;}="";
|
||||
public long AutoRuleVersion {get;set;}
|
||||
public string AutoKnowledgeId {get;set;}="";
|
||||
public long AutoKnowledgeVersion {get;set;}
|
||||
public string AutoDay {get;set;}="";
|
||||
public string AutoEpoch {get;set;}="";
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString("N");
|
||||
public string State { get; set; } = "Pending";
|
||||
public string Recipient { get; set; } = "";
|
||||
|
||||
@@ -34,6 +34,7 @@ builder.Services.AddHttpClient<OhipClient>(c => c.Timeout = TimeSpan.FromSeconds
|
||||
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.AddTransient<AutoReplyWork>();
|
||||
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
|
||||
{
|
||||
o.Cookie.Name = "guestops.session"; o.Cookie.HttpOnly = true; o.Cookie.SameSite = SameSiteMode.Lax;
|
||||
@@ -130,6 +131,7 @@ if (preview) app.MapPost("/api/preview/start", async (HttpContext c, Cancellatio
|
||||
var api = app.MapGroup("/api").RequireAuthorization();
|
||||
PmsEndpoints.Map(api,preview);
|
||||
PaymentEndpoints.Map(api,preview);
|
||||
AutoReplyEndpoints.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) =>
|
||||
{
|
||||
@@ -219,6 +221,12 @@ api.MapPost("/conversations/{id}/send", async (string id, SendInput input, HttpC
|
||||
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/release",async(string id,VersionInput input,HttpContext c,AutoReplyWork work)=>
|
||||
{
|
||||
var item=await store.Get<Conversation>(Session.Hotel(c),id);if(item==null)return Results.NotFound();
|
||||
if(preview||!await work.ReturnToStaff(item,input.Version))return Input.Conflict();
|
||||
await Session.Audit(store,c,"Returned an unsubmitted automatic reply to staff review");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();
|
||||
|
||||
@@ -18,12 +18,13 @@ public static class ReplyMime
|
||||
var encodedSubject = string.Join("\r\n ", chunks.Select(x => "=?UTF-8?B?" + Convert.ToBase64String(Encoding.UTF8.GetBytes(x)) + "?="));
|
||||
var body = Convert.ToBase64String(Encoding.UTF8.GetBytes(d.Body), Base64FormattingOptions.InsertLineBreaks);
|
||||
var date = d.UpdatedAt.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss +0000", System.Globalization.CultureInfo.InvariantCulture);
|
||||
var raw = $"From: {mailbox.Email}\r\nTo: {d.Recipient}\r\nDate: {date}\r\nSubject: {encodedSubject}\r\nMessage-ID: {d.MessageId}\r\nIn-Reply-To: {message.RfcMessageId}\r\nReferences: {message.RfcMessageId}\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n{body}\r\n";
|
||||
var automaticHeaders=d.Automatic?"Auto-Submitted: auto-replied\r\nX-Auto-Response-Suppress: All\r\n":"";
|
||||
var raw = $"{automaticHeaders}From: {mailbox.Email}\r\nTo: {d.Recipient}\r\nDate: {date}\r\nSubject: {encodedSubject}\r\nMessage-ID: {d.MessageId}\r\nIn-Reply-To: {message.RfcMessageId}\r\nReferences: {message.RfcMessageId}\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n{body}\r\n";
|
||||
return Convert.ToBase64String(Encoding.UTF8.GetBytes(raw)).TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ReplyDelivery(IStore store, GoogleMailbox google)
|
||||
public sealed class ReplyDelivery(IStore store, GoogleMailbox google, IConfiguration? config = null)
|
||||
{
|
||||
public async Task Process(Conversation message, CancellationToken ct)
|
||||
{
|
||||
@@ -48,8 +49,10 @@ public sealed class ReplyDelivery(IStore store, GoogleMailbox google)
|
||||
var hotel = await store.Get<Hotel>(message.HotelId, message.HotelId);
|
||||
var mailbox = await store.Get<Mailbox>(message.HotelId, message.MailboxId);
|
||||
if (hotel?.StaffSendingEnabled != true || mailbox?.CanSend != true || mailbox.Status != "Connected" || !google.SendingConfigured) throw new InvalidOperationException("Sending disabled.");
|
||||
if(!await AutoReplyWork.CanDeliver(store,config,message))throw new InvalidOperationException("Automatic approval no longer valid.");
|
||||
raw = ReplyMime.Build(message, mailbox);
|
||||
token = await google.AccessToken(mailbox, ct);
|
||||
if(message.Delivery.Automatic&&(!await google.AutoReplyThreadUnchanged(message,token,ct)||!await AutoReplyWork.CanDeliver(store,config,message)))throw new InvalidOperationException("Automatic reply no longer eligible.");
|
||||
ct.ThrowIfCancellationRequested();
|
||||
}
|
||||
catch { await Save("Rejected", "Nothing was sent. Check reply metadata, hotel controls and Google connection, then retry the approved reply."); return; }
|
||||
|
||||
@@ -23,6 +23,8 @@ public interface IStore
|
||||
Task<List<Conversation>> Deliveries();
|
||||
Task<bool> TryInsertPmsChange(PmsChange change);
|
||||
Task<bool> TryInsertPayment(PaymentRequest payment);
|
||||
Task<bool> TryAutoReplyClaim(AutoReplyClaim claim);
|
||||
Task<List<Conversation>> AutoReplyCandidates(string hotel,string mailbox,DateTime since);
|
||||
}
|
||||
public sealed class MongoStore : IStore
|
||||
{
|
||||
@@ -43,6 +45,8 @@ public sealed class MongoStore : IStore
|
||||
}
|
||||
public async Task Initialize()
|
||||
{
|
||||
foreach(var field in new[]{"ThreadKey","RecipientDay","DaySlot"})await Collection<AutoReplyClaim>().Indexes.CreateOneAsync(new CreateIndexModel<AutoReplyClaim>(Builders<AutoReplyClaim>.IndexKeys.Ascending(x=>x.HotelId).Ascending(field),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.AutoReplyCheckedAt).Ascending(x=>x.ReceivedAt)));
|
||||
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"})}));
|
||||
@@ -101,6 +105,11 @@ public sealed class MongoStore : IStore
|
||||
try { await Insert(message); }
|
||||
catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey) { /* already durable */ }
|
||||
}
|
||||
public Task<List<Conversation>> AutoReplyCandidates(string hotel,string mailbox,DateTime since)=>Collection<Conversation>().Find(Scope<Conversation>(hotel)&Builders<Conversation>.Filter.Eq(x=>x.MailboxId,mailbox)&Builders<Conversation>.Filter.Eq(x=>x.AutoReplyCheckedAt,null)&Builders<Conversation>.Filter.Gte(x=>x.ReceivedAt,since)).SortBy(x=>x.ReceivedAt).Limit(100).ToListAsync();
|
||||
public async Task<bool> TryAutoReplyClaim(AutoReplyClaim claim)
|
||||
{
|
||||
try{await Insert(claim);return true;}catch(MongoWriteException ex) when(ex.WriteError.Category==ServerErrorCategory.DuplicateKey){return false;}
|
||||
}
|
||||
public async Task<bool> TryInsertPayment(PaymentRequest payment)
|
||||
{
|
||||
try { await Insert(payment);return true; }
|
||||
@@ -116,6 +125,11 @@ public sealed class MongoStore : IStore
|
||||
// Explicit Development-only preview store. Production never falls back to this.
|
||||
public sealed class PreviewStore : IStore
|
||||
{
|
||||
public async Task<List<Conversation>> AutoReplyCandidates(string hotel,string mailbox,DateTime since)=>(await List<Conversation>(hotel)).Where(x=>x.MailboxId==mailbox&&x.AutoReplyCheckedAt==null&&x.ReceivedAt>=since).OrderBy(x=>x.ReceivedAt).Take(100).ToList();
|
||||
public Task<bool> TryAutoReplyClaim(AutoReplyClaim claim)
|
||||
{
|
||||
lock(gate){if(rows.Where(x=>x.Key.StartsWith("AutoReplyClaim:")).Select(x=>Clone<AutoReplyClaim>(x.Value)).Any(x=>x.HotelId==claim.HotelId&&(x.ThreadKey==claim.ThreadKey||x.RecipientDay==claim.RecipientDay||x.DaySlot==claim.DaySlot)))return Task.FromResult(false);return Task.FromResult(rows.TryAdd(Key<AutoReplyClaim>(claim.Id),Json(claim)));}
|
||||
}
|
||||
public Task<bool> TryInsertPayment(PaymentRequest payment)
|
||||
{
|
||||
lock(gate)
|
||||
|
||||
@@ -13,6 +13,8 @@ var keyPath = builder.Configuration["Keys:Path"] ?? throw new InvalidOperationEx
|
||||
builder.Services.AddDataProtection().SetApplicationName("GuestOps-Web").PersistKeysToFileSystem(new DirectoryInfo(keyPath));
|
||||
builder.Services.AddHttpClient<GoogleMailbox>(c => c.Timeout = TimeSpan.FromSeconds(25)).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
builder.Services.AddTransient<ReplyDelivery>();
|
||||
builder.Services.AddTransient<AutoReplyWork>();
|
||||
builder.Services.AddHostedService<AutoReplyWorker>();
|
||||
builder.Services.AddHostedService<DeliveryWorker>();
|
||||
builder.Services.AddHostedService<MailboxWorker>();
|
||||
await builder.Build().RunAsync();
|
||||
@@ -69,3 +71,27 @@ sealed class DeliveryWorker(IStore store, IServiceScopeFactory factory, ILogger<
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sealed class AutoReplyWorker(IStore store,IServiceScopeFactory factory,ILogger<AutoReplyWorker> log):BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
await store.Initialize();
|
||||
while(!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach(var box in await store.Mailboxes())
|
||||
{
|
||||
var hotel=await store.Get<Hotel>(box.HotelId,box.HotelId);if(hotel==null||hotel.AutoReplyMode=="Off")continue;
|
||||
foreach(var message in await store.AutoReplyCandidates(box.HotelId,box.Id,hotel.AutoReplySince))
|
||||
{
|
||||
stoppingToken.ThrowIfCancellationRequested();using var scope=factory.CreateScope();await scope.ServiceProvider.GetRequiredService<AutoReplyWork>().Process(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(Exception ex) when(!stoppingToken.IsCancellationRequested){log.LogWarning("FAQ automation cycle paused ({Type})",ex.GetType().Name);}
|
||||
await Task.Delay(TimeSpan.FromSeconds(30),stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user