Add controlled FAQ auto-replies with test mode and durable sending limits

This commit is contained in:
wolf-demon
2026-09-15 09:50:52 +01:00
parent ad57a8b1bd
commit 5a93c35b18
20 changed files with 389 additions and 16 deletions
+23
View File
@@ -0,0 +1,23 @@
import {useEffect,useState} from 'react';
import {api,type Hotel,type Knowledge} from './api';
type Rule={id:string;question:string;knowledgeId:string;knowledgeVersion:number;enabled:boolean;version:number};
type Status={liveConfigured:boolean;preview:boolean;questions:string[];dailyLimit:number};
type Decision={matches:boolean;reason:string;body:string};
type History={id:string;subject:string;from:string;autoReplyCheckedAt:string;autoReplyMatched:boolean;autoReplyDetail:string;delivery:string|null};
type Props={hotel:Hotel;owner:boolean;busy:boolean;run:(f:()=>Promise<void>)=>Promise<void>;onHotel:(h:Hotel)=>void};
export function AutomationPage({hotel,owner,busy,run,onHotel}:Props){
const [status,setStatus]=useState<Status|null>(null),[rules,setRules]=useState<Rule[]>([]),[knowledge,setKnowledge]=useState<Knowledge[]>([]),[history,setHistory]=useState<History[]>([]);
const [question,setQuestion]=useState(0),[answer,setAnswer]=useState(''),[enabled,setEnabled]=useState(false),[subject,setSubject]=useState('Parking question'),[body,setBody]=useState('Is parking available?'),[result,setResult]=useState<Decision|null>(null);
async function refresh(){const [s,r,k,h]=await Promise.all([api<Status>('/auto-replies/status'),api<Rule[]>('/auto-replies/rules'),api<Knowledge[]>('/knowledge'),api<History[]>('/auto-replies/history')]);setStatus(s);setRules(r);setKnowledge(k);setHistory(h);}
useEffect(()=>{run(refresh);},[hotel.id]);
const current=rules.find(r=>r.question===status?.questions[question]);
useEffect(()=>{setAnswer(current?.knowledgeId||'');setEnabled(current?.enabled||false);},[question,current?.id,current?.version]);
async function mode(value:string){await run(async()=>{if(value==='Live'&&!window.confirm('Enable automatic FAQ sending for new incoming messages? Confirm that you reviewed test-mode results and accepted Gmail delivery with a sandbox mailbox. Up to 20 replies per hotel per UTC day may be sent.'))return;onHotel(await api<Hotel>('/auto-replies/mode','PUT',{mode:value,version:hotel.version,acceptanceConfirmed:value==='Live'}));});}
async function save(e:React.FormEvent){e.preventDefault();await run(async()=>{const item=await api<Rule>(`/auto-replies/rules/${question}`,'PUT',{question:status!.questions[question],knowledgeId:answer,enabled,version:current?.version||0});setRules(old=>[item,...old.filter(r=>r.id!==item.id)]);setResult(null);});}
return <div className="page"><div className="heading-row"><div className="page-heading"><span className="eyebrow">Simple questions, thoughtful answers</span><h1>FAQ automation</h1><p>Start in test mode. Let approved answers handle a small set of straightforward questions.</p></div><button className="button secondary" disabled={busy} onClick={()=>run(refresh)}>Refresh results</button></div>
<section className="settings-card"><h2>Automation mode: {hotel.autoReplyMode||'Off'}</h2><p>Only exact, complete FAQ questions qualify. Extra requests, attachments and conversations already in progress stay with your team.</p><div className="form-actions"><button className="button secondary" disabled={busy||!owner} onClick={()=>mode('Off')}>Turn off</button><button className="button secondary" disabled={busy||!owner} onClick={()=>mode('Test')}>Use test mode</button><button className="button primary" disabled={busy||!owner||!status?.liveConfigured||!hotel.staffSendingEnabled} onClick={()=>mode('Live')}>Enable live replies</button></div><p className="small muted">Test mode sends nothing. Live mode requires administrator enablement and Gmail sending. Each mode change starts with new incoming messages; existing inbox messages are not sent automatically.</p><p className="small muted">Maximum 20 automatic replies per hotel per UTC day, one per sender per UTC day, and one per Gmail thread. Turning off stops queued replies when the worker next checks them; a request already submitted to Gmail cannot be recalled.</p>{status?.preview&&<p className="staff-note">Sample workspace: the question tester works here. Live sending is disabled.</p>}</section>
<div className="pms-columns"><section className="settings-card"><h2>Review a FAQ rule</h2><form onSubmit={save}><fieldset disabled={busy||!owner}><label>Complete guest question<select value={question} onChange={e=>setQuestion(Number(e.target.value))}>{status?.questions.map((q,i)=><option value={i} key={q}>{q}</option>)}</select></label><label>Approved hotel answer<select value={answer} required onChange={e=>setAnswer(e.target.value)}><option value="">Choose an answer</option>{knowledge.filter(k=>k.approved).map(k=><option value={k.id} key={k.id}>{k.title}</option>)}</select></label>{answer&&<p className="staff-note">{knowledge.find(k=>k.id===answer)?.answer}</p>}<label className="checkbox-label"><input type="checkbox" checked={enabled} onChange={e=>setEnabled(e.target.checked)}/>Enable this exact question and reviewed answer</label><button className="button secondary">Save reviewed rule</button></fieldset></form><p className="small muted">The approved answer is sent exactly as saved, with the hotel signature. Editing the answer pauses matching until this rule is reviewed and saved again.</p></section>
<section className="settings-card"><h2>Try a question</h2><form onSubmit={e=>{e.preventDefault();run(async()=>setResult(await api<Decision>('/auto-replies/test','POST',{subject,body})));}}><fieldset disabled={busy||!owner}><label>Subject<input value={subject} maxLength={200} onChange={e=>setSubject(e.target.value)}/></label><label>Complete message<textarea rows={4} value={body} maxLength={2000} required onChange={e=>setBody(e.target.value)}/></label><button className="button secondary">Check match without sending</button></fieldset></form>{result&&<div role="status" className="staff-note"><strong>{result.matches?'Content matches a reviewed rule':'Keep with staff'}</strong><p>{result.reason}</p>{result.body&&<p>{result.body}</p>}</div>}<p className="small muted">This tester checks content only. Real messages must also pass sender, recipient, age, thread and delivery-limit checks.</p></section></div>
<section className="settings-card"><h2>Recent incoming-message results</h2>{history.length===0?<p>No incoming messages have been evaluated yet. Enable test mode after connecting your mailbox.</p>:<div className="pms-history">{history.map(h=><div className="pms-history-item" key={h.id}><strong>{h.subject}</strong><span>{h.autoReplyDetail}</span><span>{h.delivery?`Delivery: ${h.delivery} · `:''}{new Date(h.autoReplyCheckedAt).toLocaleString()}</span></div>)}</div>}</section>
</div>;
}
+6 -4
View File
@@ -21,11 +21,13 @@ export function ReplyActions({message,hotel,mailboxes,knowledge,dirty,busy,run,o
const act=(action:string)=>run(async()=>onUpdate(await api<Conversation>(`/conversations/${message.id}/delivery/${action}`,'POST',{version:message.version})));
const canSend=hotel.staffSendingEnabled&&mailboxes.sendingConfigured&&mailboxes.items.some(m=>m.id===message.mailboxId&&m.canSend);
return <section className="reply-actions" aria-label="Reply review and delivery">
{message.autoReplyDetail&&<p className="staff-note">FAQ check: {message.autoReplyDetail}</p>}
{delivery?.automatic&&<p className="small muted">This reply uses an owner-approved FAQ rule.</p>}
{message.draftReviewNote&&<p className="staff-note">AI review: {message.draftReviewNote}</p>}
{!!message.draftSources?.length&&<details><summary>Hotel answers referenced by this draft</summary>{message.draftSources.map(id=>{const source=knowledge.find(k=>k.id===id);return <div key={id}><strong>{source?.title||'Answer no longer available'}</strong><p>{source?.answer||'Ask your hotel owner to check this information.'}</p>{source&&!source.approved&&<p>This answer is no longer approved. Check the draft before sending.</p>}</div>;})}</details>}
{delivery?<div role="status"><strong>Delivery: {delivery.state==='NeedsReview'?'Needs verification':delivery.state}</strong><p>{delivery.detail}</p><p className="small">To: {delivery.recipient}</p>{delivery.state==='Rejected'&&<button className="button secondary" disabled={busy} onClick={()=>act('retry')}>Retry approved reply</button>}{delivery.state==='NeedsReview'&&<><button className="button secondary" disabled={busy} onClick={()=>act('verify')}>Verify in Gmail Sent</button><p className="small">Reference: {delivery.messageId}. An uncertain reply is never automatically resent.</p></>}</div>:<>
{delivery?<div role="status"><strong>Delivery: {delivery.state==='NeedsReview'?'Needs verification':delivery.state}</strong><p>{delivery.detail}</p><p className="small">To: {delivery.recipient}</p>{delivery.state==='Rejected'&&<button className="button secondary" disabled={busy} onClick={()=>act(delivery.automatic?'release':'retry')}>{delivery.automatic?'Return to staff review':'Retry approved reply'}</button>}{delivery.state==='NeedsReview'&&<><button className="button secondary" disabled={busy} onClick={()=>act('verify')}>Verify in Gmail Sent</button><p className="small">Reference: {delivery.messageId}. An uncertain reply is never automatically resent.</p></>}</div>:<>
<div className="form-actions"><button className="button secondary" disabled={busy||dirty||!hotel.aiDraftsEnabled||!mailboxes.aiConfigured} onClick={generate}>Generate AI draft</button><button className="button primary" disabled={busy||dirty||!canSend||!message.draft.trim()||!message.replyAddress} onClick={send}>Review and send</button></div>
<p className="small muted">{dirty?'Save your changes before generating or sending.':canSend?`Reply to: ${message.replyAddress||'Unavailable — open this message in Gmail'}. Sending always requires your approval.`:'Staff sending is not enabled for this mailbox. Your hotel owner can configure it in Settings.'}</p>
<p className="small muted">{dirty?'Save your changes before generating or sending.':canSend?`Reply to: ${message.replyAddress||'Unavailable — open this message in Gmail'}. This manual reply requires your approval.`:'Staff sending is not enabled for this mailbox. Your hotel owner can configure it in Settings.'}</p>
{!hotel.aiDraftsEnabled&&<p className="small muted">AI drafts are off. Your hotel owner can enable them after the administrator configures AI.</p>}
</>}
</section>;
@@ -33,8 +35,8 @@ export function ReplyActions({message,hotel,mailboxes,knowledge,dirty,busy,run,o
export function ReplyControls({hotel,mailboxes,owner,busy,run,onSave}:{hotel:Hotel;mailboxes:Mailboxes;owner:boolean;busy:boolean;run:Run;onSave:(hotel:Hotel)=>void}) {
const update=(field:'aiDraftsEnabled'|'staffSendingEnabled',value:boolean)=>run(async()=>{
if(value&&!window.confirm(field==='aiDraftsEnabled'?'Enable AI drafts? Message text and selected approved hotel answers will be sent to the configured OpenAI service when staff request a draft.':'Enable staff-approved Gmail sending for this hotel? Each reply will still require a staff member to review and approve it.'))return;
if(value&&!window.confirm(field==='aiDraftsEnabled'?'Enable AI drafts? Message text and selected approved hotel answers will be sent to the configured OpenAI service when staff request a draft.':'Enable staff-approved Gmail sending for this hotel? Staff replies require review. If FAQ live mode is enabled separately, its approved rules can also send automatically.'))return;
onSave(await api<Hotel>('/reply-controls','PUT',{version:hotel.version,aiDraftsEnabled:hotel.aiDraftsEnabled,staffSendingEnabled:hotel.staffSendingEnabled,[field]:value}));
});
return <section className="settings-card"><h2>Reply controls</h2><p>Your team reviews every reply. Automatic replies remain off.</p><label className="checkbox-label"><input type="checkbox" checked={hotel.aiDraftsEnabled||false} disabled={!owner||busy||(!mailboxes.aiConfigured&&!hotel.aiDraftsEnabled)} onChange={e=>update('aiDraftsEnabled',e.target.checked)}/>AI drafts from approved hotel knowledge</label><p className="small muted">{mailboxes.aiConfigured?'Only requested drafts use AI. Check all facts before sending.':'Your administrator must configure the AI API key and model first.'}</p><label className="checkbox-label"><input type="checkbox" checked={hotel.staffSendingEnabled||false} disabled={!owner||busy||(!mailboxes.sendingConfigured&&!hotel.staffSendingEnabled)} onChange={e=>update('staffSendingEnabled',e.target.checked)}/>Allow staff to approve and send replies</label><p className="small muted">{mailboxes.sendingConfigured?'Reconnect Google to grant send permission if it was previously read-only.':'Your administrator must enable Google sending first.'}</p></section>;
return <section className="settings-card"><h2>Reply controls</h2><p>Staff replies require review. FAQ automation is controlled separately on the FAQ automation page.</p><label className="checkbox-label"><input type="checkbox" checked={hotel.aiDraftsEnabled||false} disabled={!owner||busy||(!mailboxes.aiConfigured&&!hotel.aiDraftsEnabled)} onChange={e=>update('aiDraftsEnabled',e.target.checked)}/>AI drafts from approved hotel knowledge</label><p className="small muted">{mailboxes.aiConfigured?'Only requested drafts use AI. Check all facts before sending.':'Your administrator must configure the AI API key and model first.'}</p><label className="checkbox-label"><input type="checkbox" checked={hotel.staffSendingEnabled||false} disabled={!owner||busy||(!mailboxes.sendingConfigured&&!hotel.staffSendingEnabled)} onChange={e=>update('staffSendingEnabled',e.target.checked)}/>Allow staff to approve and send replies</label><p className="small muted">{mailboxes.sendingConfigured?'Reconnect Google to grant send permission if it was previously read-only.':'Your administrator must enable Google sending first.'}</p></section>;
}
+2 -2
View File
@@ -1,7 +1,7 @@
export type User = { id: string; name: string; role: string; hotelId: string };
export type Session = { preview: boolean; csrfToken: string; user: User | null };
export type Hotel = { id: string; name: string; timezone: string; signature: string; replyMode: string; version: number; aiDraftsEnabled: boolean; staffSendingEnabled: boolean; paymentsEnabled: boolean; pmsUpdatesEnabled: boolean };
export type Conversation = { id: string; from: string; subject: string; body: string; receivedAt: string; status: string; draft: string; category: string; note: string; providerThreadId: string; version: number; mailboxId: string; replyAddress: string; draftSources: string[]; draftReviewNote: string; delivery: { state: string; recipient: string; body: string; detail: string; messageId: string; providerId: string } | null };
export type Hotel = { id: string; name: string; timezone: string; signature: string; replyMode: string; version: number; aiDraftsEnabled: boolean; staffSendingEnabled: boolean; autoReplyMode: string; paymentsEnabled: boolean; pmsUpdatesEnabled: boolean };
export type Conversation = { id: string; from: string; subject: string; body: string; receivedAt: string; status: string; draft: string; category: string; note: string; providerThreadId: string; version: number; mailboxId: string; autoReplyDetail: string; replyAddress: string; draftSources: string[]; draftReviewNote: string; delivery: { automatic: boolean; state: string; recipient: string; body: string; detail: string; messageId: string; providerId: string } | null };
export type Knowledge = { id: string; title: string; category: string; answer: string; keywords: string; approved: boolean; version: number };
export type Activity = { id: string; at: string; userName: string; action: string };
export type Mailboxes = { configured: boolean; aiConfigured?: boolean; sendingConfigured?: boolean; items: { id: string; email: string; status: string; lastSyncAt: string | null; syncError: string; canSend: boolean }[] };
+5 -4
View File
@@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client';
import { Inbox, BookOpen, Settings, Activity as ActivityIcon, Search, ArrowUpRight, ChevronDown, Check, CheckCheck, Clock3, FileText, LogOut, RefreshCw, ArrowLeft, Plus, X, Mail, ShieldCheck, Save, CircleHelp, Banknote, Building2, ChevronRight } from 'lucide-react';
import { api, session, type Session, type Hotel, type Conversation, type Knowledge, type Activity, type Mailboxes } from './api';
import './style.css';
import { AutomationPage } from './AutomationPage';
import { PaymentsPage } from './PaymentsPage';
import { PmsPage } from './PmsPage';
import { ReplyActions, ReplyControls } from './ReplyActions';
@@ -38,13 +39,13 @@ function App() {
<a href="/inbox" aria-label="GuestOps inbox" className="brand" onClick={e=>{e.preventDefault();go('/inbox');}}><span className="brand-mark">g</span><span>guestops<span className="brand-dot">.</span></span></a>
<div className="hotel-switch"><span className="hotel-icon"><Building2 size={19}/></span><div><strong>{hotel?.name||'Your hotel'}</strong><small>Hotel workspace</small></div></div>
<div className="nav-label">WORKSPACE</div>
<nav aria-label="Main navigation">{[{path:'/inbox',label:'Inbox',icon:Inbox},{path:'/reservations',label:'Reservations',icon:Building2},{path:'/payments',label:'Payments',icon:Banknote},{path:'/knowledge',label:'Hotel knowledge',icon:BookOpen},{path:'/activity',label:'Activity',icon:ActivityIcon},{path:'/settings',label:'Settings',icon:Settings}].map(n=><a key={n.path} href={n.path} aria-label={n.label} title={n.label} className={page===n.path?'nav-item active':'nav-item'} aria-current={page===n.path?'page':undefined} onClick={e=>{e.preventDefault();go(n.path);}}><n.icon size={20}/><span>{n.label}</span>{n.path==='/inbox'&&count>0&&<b>{count}</b>}</a>)}</nav>
<div className="sidebar-bottom"><div className="mode-card"><ShieldCheck size={20}/><strong>You're in control</strong><p>Replies stay as drafts until your team reviews them.</p></div><div className="profile"><span className="avatar profile-avatar">{initials(auth.user.name)}</span><div><strong>{auth.user.name}</strong><small>{auth.user.role==='Owner'?'Hotel owner':'Team member'}</small></div><button className="icon-button" onClick={logout} disabled={busy} aria-label="Sign out"><LogOut size={18}/></button></div></div>
<nav aria-label="Main navigation">{[{path:'/inbox',label:'Inbox',icon:Inbox},{path:'/reservations',label:'Reservations',icon:Building2},{path:'/payments',label:'Payments',icon:Banknote},{path:'/automation',label:'FAQ automation',icon:ShieldCheck},{path:'/knowledge',label:'Hotel knowledge',icon:BookOpen},{path:'/activity',label:'Activity',icon:ActivityIcon},{path:'/settings',label:'Settings',icon:Settings}].map(n=><a key={n.path} href={n.path} aria-label={n.label} title={n.label} className={page===n.path?'nav-item active':'nav-item'} aria-current={page===n.path?'page':undefined} onClick={e=>{e.preventDefault();go(n.path);}}><n.icon size={20}/><span>{n.label}</span>{n.path==='/inbox'&&count>0&&<b>{count}</b>}</a>)}</nav>
<div className="sidebar-bottom"><div className="mode-card"><ShieldCheck size={20}/><strong>You're in control</strong><p>Your team controls approved answers and reply automation.</p></div><div className="profile"><span className="avatar profile-avatar">{initials(auth.user.name)}</span><div><strong>{auth.user.name}</strong><small>{auth.user.role==='Owner'?'Hotel owner':'Team member'}</small></div><button className="icon-button" onClick={logout} disabled={busy} aria-label="Sign out"><LogOut size={18}/></button></div></div>
</aside>
<main className="main">
<header className="topbar"><span><span className="breadcrumb">Workspace</span><ChevronRight size={14}/>{page==='/inbox'?'Inbox':page==='/knowledge'?'Hotel knowledge':page==='/activity'?'Activity':page==='/reservations'?'Reservations':page==='/payments'?'Payments':'Settings'}</span><div className="topbar-right">{auth.preview&&<span className="preview-pill">Preview · sample data</span>}<span className="draft-mode"><span/>{hotel?.staffSendingEnabled?'Staff-approved sending':'Draft-only mode'}</span><button className="icon-button" aria-label="Refresh workspace" disabled={busy} onClick={()=>run(refresh)}><RefreshCw size={17}/></button></div></header>
<header className="topbar"><span><span className="breadcrumb">Workspace</span><ChevronRight size={14}/>{page==='/inbox'?'Inbox':page==='/knowledge'?'Hotel knowledge':page==='/activity'?'Activity':page==='/reservations'?'Reservations':page==='/payments'?'Payments':page==='/automation'?'FAQ automation':'Settings'}</span><div className="topbar-right">{auth.preview&&<span className="preview-pill">Preview · sample data</span>}<span className="draft-mode"><span/>{hotel?.autoReplyMode==='Live'?'FAQ auto-replies enabled':hotel?.staffSendingEnabled?'Staff-approved sending':'Draft-only mode'}</span><button className="icon-button" aria-label="Refresh workspace" disabled={busy} onClick={()=>run(refresh)}><RefreshCw size={17}/></button></div></header>
{errorBox}{notice&&<div className="toast" role="status"><Check size={17}/>{notice}</div>}
{!loaded?<div className="loading"><p>Loading your hotel…</p></div>:page==='/inbox'?<InboxPage hotel={hotel!} mailboxes={mailboxes} conversations={conversations} knowledge={knowledge} busy={busy} run={run} onUpdate={c=>setConversations(old=>old.map(x=>x.id===c.id?c:x))} notify={setNotice} go={go}/>:page==='/payments'?<PaymentsPage hotel={hotel!} owner={auth.user.role==='Owner'} busy={busy} run={run} onHotel={setHotel}/>:page==='/reservations'?<PmsPage hotel={hotel!} owner={auth.user.role==='Owner'} busy={busy} run={run} onHotel={setHotel}/>:page==='/knowledge'?<KnowledgePage items={knowledge} canEdit={auth.user.role==='Owner'} busy={busy} run={run} onUpdate={item=>setKnowledge(old=>old.some(x=>x.id===item.id)?old.map(x=>x.id===item.id?item:x):[...old,item])} notify={setNotice}/>:page==='/activity'?<div className="page"><PageHeading eyebrow="A clear record" title="Workspace activity" text="Changes made by your team, in one place."/><div className="activity-list">{activity.length?activity.map(a=><div className="activity-row" key={a.id}><span className="activity-icon"><Check size={18}/></span><div><strong>{a.action}</strong><p>{a.userName}</p></div><time>{date(a.at)}</time></div>):<Empty title="No activity yet" text="Changes to your workspace will appear here."/>}</div></div>:<SettingsPage hotel={hotel!} mailboxes={mailboxes} preview={auth.preview} owner={auth.user.role==='Owner'} busy={busy} run={run} onSave={h=>{setHotel(h);setNotice('Hotel settings saved.');}}/>}
{!loaded?<div className="loading"><p>Loading your hotel…</p></div>:page==='/inbox'?<InboxPage hotel={hotel!} mailboxes={mailboxes} conversations={conversations} knowledge={knowledge} busy={busy} run={run} onUpdate={c=>setConversations(old=>old.map(x=>x.id===c.id?c:x))} notify={setNotice} go={go}/>:page==='/automation'?<AutomationPage hotel={hotel!} owner={auth.user.role==='Owner'} busy={busy} run={run} onHotel={setHotel}/>:page==='/payments'?<PaymentsPage hotel={hotel!} owner={auth.user.role==='Owner'} busy={busy} run={run} onHotel={setHotel}/>:page==='/reservations'?<PmsPage hotel={hotel!} owner={auth.user.role==='Owner'} busy={busy} run={run} onHotel={setHotel}/>:page==='/knowledge'?<KnowledgePage items={knowledge} canEdit={auth.user.role==='Owner'} busy={busy} run={run} onUpdate={item=>setKnowledge(old=>old.some(x=>x.id===item.id)?old.map(x=>x.id===item.id?item:x):[...old,item])} notify={setNotice}/>:page==='/activity'?<div className="page"><PageHeading eyebrow="A clear record" title="Workspace activity" text="Changes made by your team, in one place."/><div className="activity-list">{activity.length?activity.map(a=><div className="activity-row" key={a.id}><span className="activity-icon"><Check size={18}/></span><div><strong>{a.action}</strong><p>{a.userName}</p></div><time>{date(a.at)}</time></div>):<Empty title="No activity yet" text="Changes to your workspace will appear here."/>}</div></div>:<SettingsPage hotel={hotel!} mailboxes={mailboxes} preview={auth.preview} owner={auth.user.role==='Owner'} busy={busy} run={run} onSave={h=>{setHotel(h);setNotice('Hotel settings saved.');}}/>}
</main>
</div>;
}