feat: add Twilio SMS/call integration with settings, templates, and conversation history

This commit is contained in:
Gitead
2026-05-02 20:18:58 -04:00
parent b73b8c97c6
commit 5689269690
17 changed files with 770 additions and 196 deletions

View File

@@ -21,10 +21,7 @@ export function MessageThread({ patient, onBack }: MessageThreadProps) {
const { data: communications = [], isLoading } = useQuery<Communication[]>({
queryKey: ["/api/patients", patient.id, "communications"],
queryFn: async () => {
const res = await fetch(`/api/patients/${patient.id}/communications`, {
credentials: "include",
});
if (!res.ok) throw new Error("Failed to fetch communications");
const res = await apiRequest("GET", `/api/patients/${patient.id}/communications`);
return res.json();
},
refetchInterval: 5000, // Refresh every 5 seconds to get new messages

View File

@@ -1,5 +1,5 @@
import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { useState, useEffect } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -18,9 +18,9 @@ import {
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { MessageSquare, Send, Loader2 } from "lucide-react";
import { MessageSquare, Send, Loader2, Save } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { apiRequest, queryClient } from "@/lib/queryClient";
import type { Patient } from "@repo/db/types";
interface SmsTemplateDialogProps {
@@ -29,119 +29,109 @@ interface SmsTemplateDialogProps {
patient: Patient | null;
}
const MESSAGE_TEMPLATES = {
const DEFAULT_TEMPLATES: Record<string, { name: string; body: string }> = {
appointment_reminder: {
name: "Appointment Reminder",
template: (firstName: string) =>
body: (firstName: string) =>
`Hi ${firstName}, this is your dental office. Reminder: You have an appointment scheduled. Please confirm or call us if you need to reschedule.`,
},
} as any,
appointment_confirmation: {
name: "Appointment Confirmation",
template: (firstName: string) =>
body: (firstName: string) =>
`Hi ${firstName}, your appointment has been confirmed. We look forward to seeing you! If you have any questions, please call our office.`,
},
} as any,
follow_up: {
name: "Follow-Up",
template: (firstName: string) =>
body: (firstName: string) =>
`Hi ${firstName}, thank you for visiting our dental office. How are you feeling after your treatment? Please let us know if you have any concerns.`,
},
} as any,
payment_reminder: {
name: "Payment Reminder",
template: (firstName: string) =>
body: (firstName: string) =>
`Hi ${firstName}, this is a friendly reminder about your outstanding balance. Please contact our office to discuss payment options.`,
},
} as any,
general: {
name: "General Message",
template: (firstName: string) =>
`Hi ${firstName}, this is your dental office. `,
},
body: (firstName: string) => `Hi ${firstName}, this is your dental office. `,
} as any,
custom: {
name: "Custom Message",
template: () => "",
},
body: () => "",
} as any,
};
const TEMPLATE_KEYS = Object.keys(DEFAULT_TEMPLATES);
function getDefaultBody(key: string, firstName: string): string {
const t = DEFAULT_TEMPLATES[key];
if (!t) return "";
return typeof t.body === "function" ? (t.body as any)(firstName) : t.body;
}
export function SmsTemplateDialog({
open,
onOpenChange,
patient,
}: SmsTemplateDialogProps) {
const [selectedTemplate, setSelectedTemplate] = useState<
keyof typeof MESSAGE_TEMPLATES
>("appointment_reminder");
const [customMessage, setCustomMessage] = useState("");
const [selectedKey, setSelectedKey] = useState("appointment_reminder");
const [messageText, setMessageText] = useState("");
const { toast } = useToast();
const sendSmsMutation = useMutation({
mutationFn: async ({
to,
message,
patientId,
}: {
to: string;
message: string;
patientId: number;
}) => {
const { data: savedTemplates = {} } = useQuery<Record<string, string>>({
queryKey: ["/api/twilio/templates"],
enabled: open,
});
// Resolve effective body for a given key (saved override or default)
const resolveBody = (key: string) => {
if (key === "custom") return "";
if (savedTemplates[key]) {
// Replace placeholder first name with actual patient name
return savedTemplates[key].replace(/^Hi \w+,/, `Hi ${patient?.firstName ?? ""},`);
}
return getDefaultBody(key, patient?.firstName ?? "");
};
// When dialog opens or template changes, populate message
useEffect(() => {
if (open) setMessageText(resolveBody(selectedKey));
}, [open, selectedKey, savedTemplates, patient?.firstName]);
const sendMutation = useMutation({
mutationFn: async (message: string) => {
return apiRequest("POST", "/api/twilio/send-sms", {
to,
to: patient!.phone,
message,
patientId,
patientId: patient!.id,
});
},
onSuccess: () => {
toast({
title: "SMS Sent Successfully",
description: `Message sent to ${patient?.firstName} ${patient?.lastName}`,
});
toast({ title: "SMS Sent", description: `Message sent to ${patient?.firstName} ${patient?.lastName}` });
onOpenChange(false);
// Reset state
setSelectedTemplate("appointment_reminder");
setCustomMessage("");
setSelectedKey("appointment_reminder");
setMessageText("");
},
onError: (error: any) => {
toast({
title: "Failed to Send SMS",
description:
error.message ||
"Please check your Twilio configuration and try again.",
variant: "destructive",
});
onError: (err: any) => {
toast({ title: "Failed to Send SMS", description: err.message || "Please check your Twilio configuration.", variant: "destructive" });
},
});
const getMessage = () => {
if (!patient) return "";
const updateMutation = useMutation({
mutationFn: async ({ key, body }: { key: string; body: string }) => {
return apiRequest("PUT", `/api/twilio/templates/${key}`, { body });
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/twilio/templates"] });
toast({ title: "Template Updated", description: "This template will be used going forward." });
},
onError: (err: any) => {
toast({ title: "Failed to Update Template", description: err.message, variant: "destructive" });
},
});
if (selectedTemplate === "custom") {
return customMessage;
}
return MESSAGE_TEMPLATES[selectedTemplate].template(patient.firstName);
};
const handleSend = () => {
if (!patient || !patient.phone) return;
const message = getMessage();
if (!message.trim()) return;
sendSmsMutation.mutate({
to: patient.phone,
message: message,
patientId: Number(patient.id),
});
};
const handleTemplateChange = (value: string) => {
const templateKey = value as keyof typeof MESSAGE_TEMPLATES;
setSelectedTemplate(templateKey);
// Pre-fill custom message if not custom template
if (templateKey !== "custom" && patient) {
setCustomMessage(
MESSAGE_TEMPLATES[templateKey].template(patient.firstName)
);
}
const handleTemplateChange = (key: string) => {
setSelectedKey(key);
setMessageText(resolveBody(key));
};
return (
@@ -153,24 +143,22 @@ export function SmsTemplateDialog({
Send SMS to {patient?.firstName} {patient?.lastName}
</DialogTitle>
<DialogDescription>
Choose a message template or write a custom message
Choose a template or write a custom message
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="template">Message Template</Label>
<Select
value={selectedTemplate}
onValueChange={handleTemplateChange}
>
<SelectTrigger id="template" data-testid="select-sms-template">
<Label>Message Template</Label>
<Select value={selectedKey} onValueChange={handleTemplateChange}>
<SelectTrigger data-testid="select-sms-template">
<SelectValue placeholder="Select a template" />
</SelectTrigger>
<SelectContent>
{Object.entries(MESSAGE_TEMPLATES).map(([key, value]) => (
{TEMPLATE_KEYS.map((key) => (
<SelectItem key={key} value={key}>
{value.name}
{DEFAULT_TEMPLATES[key]?.name ?? key}
{savedTemplates[key] ? " ✎" : ""}
</SelectItem>
))}
</SelectContent>
@@ -178,13 +166,29 @@ export function SmsTemplateDialog({
</div>
<div className="space-y-2">
<Label htmlFor="message">Message Preview</Label>
<div className="flex items-center justify-between">
<Label>Message</Label>
{selectedKey !== "custom" && (
<Button
type="button"
variant="outline"
size="sm"
className="h-7 text-xs gap-1"
disabled={!messageText.trim() || updateMutation.isPending}
onClick={() => updateMutation.mutate({ key: selectedKey, body: messageText })}
>
{updateMutation.isPending ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<Save className="h-3 w-3" />
)}
{updateMutation.isPending ? "Saving..." : "Update Template"}
</Button>
)}
</div>
<Textarea
id="message"
value={
selectedTemplate === "custom" ? customMessage : getMessage()
}
onChange={(e) => setCustomMessage(e.target.value)}
value={messageText}
onChange={(e) => setMessageText(e.target.value)}
placeholder="Type your message here..."
rows={5}
className="resize-none"
@@ -203,21 +207,17 @@ export function SmsTemplateDialog({
Cancel
</Button>
<Button
onClick={handleSend}
disabled={
!patient?.phone ||
!getMessage().trim() ||
sendSmsMutation.isPending
}
onClick={() => sendMutation.mutate(messageText)}
disabled={!patient?.phone || !messageText.trim() || sendMutation.isPending || !patient}
className="gap-2"
data-testid="button-send-sms"
>
{sendSmsMutation.isPending ? (
{sendMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Send className="h-4 w-4" />
)}
{sendSmsMutation.isPending ? "Sending..." : "Send SMS"}
{sendMutation.isPending ? "Sending..." : "Send SMS"}
</Button>
</DialogFooter>
</DialogContent>

View File

@@ -0,0 +1,170 @@
import { useState, useEffect } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Card, CardContent } from "@/components/ui/card";
import { Eye, EyeOff, CheckCircle } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
type TwilioSettings = {
id?: number;
accountSid: string;
authToken: string;
phoneNumber: string;
greetingMessage?: string | null;
};
export function TwilioSettingsCard() {
const { toast } = useToast();
const [accountSid, setAccountSid] = useState("");
const [authToken, setAuthToken] = useState("");
const [phoneNumber, setPhoneNumber] = useState("");
const [greetingMessage, setGreetingMessage] = useState("");
const [showAuthToken, setShowAuthToken] = useState(false);
const { data: settings, isLoading } = useQuery<TwilioSettings | null>({
queryKey: ["/api/twilio/settings"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/twilio/settings");
if (!res.ok) return null;
return res.json();
},
});
useEffect(() => {
if (settings) {
setAccountSid(settings.accountSid ?? "");
setAuthToken(settings.authToken ?? "");
setPhoneNumber(settings.phoneNumber ?? "");
setGreetingMessage(settings.greetingMessage ?? "");
}
}, [settings]);
const saveMutation = useMutation({
mutationFn: async (data: TwilioSettings) => {
const res = await apiRequest("PUT", "/api/twilio/settings", data);
if (!res.ok) {
const err = await res.json().catch(() => null);
throw new Error(err?.message || "Failed to save Twilio settings");
}
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/twilio/settings"] });
toast({ title: "Twilio Settings Saved", description: "Your Twilio credentials have been saved." });
},
onError: (err: any) => {
toast({ title: "Error", description: err?.message || "Failed to save settings", variant: "destructive" });
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!accountSid.trim() || !authToken.trim() || !phoneNumber.trim()) return;
saveMutation.mutate({ accountSid: accountSid.trim(), authToken: authToken.trim(), phoneNumber: phoneNumber.trim(), greetingMessage: greetingMessage.trim() || null });
};
const isConfigured = !!(settings?.accountSid && settings?.authToken && settings?.phoneNumber);
return (
<Card>
<CardContent className="space-y-4 py-6">
<div className="flex items-center gap-2">
<h3 className="text-lg font-semibold">Twilio Settings</h3>
{isConfigured && (
<span className="flex items-center gap-1 text-xs text-green-600 font-medium">
<CheckCircle className="h-3.5 w-3.5" /> Configured
</span>
)}
</div>
<p className="text-sm text-gray-500">
Enter your Twilio credentials to enable SMS and calling features. Find these in your{" "}
<span className="font-medium">Twilio Console</span> Account Info.
</p>
{isLoading ? (
<p className="text-sm text-gray-400">Loading...</p>
) : (
<form className="space-y-4" onSubmit={handleSubmit}>
<div>
<label className="block text-sm font-medium">Account SID</label>
<input
type="text"
value={accountSid}
onChange={(e) => setAccountSid(e.target.value)}
className="mt-1 p-2 border rounded w-full font-mono text-sm"
placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
required
/>
</div>
<div>
<label className="block text-sm font-medium">Auth Token</label>
<div className="relative mt-1">
<input
type={showAuthToken ? "text" : "password"}
value={authToken}
onChange={(e) => setAuthToken(e.target.value)}
className="p-2 border rounded w-full pr-10 font-mono text-sm"
placeholder="••••••••••••••••••••••••••••••••"
required
/>
<button
type="button"
onClick={() => setShowAuthToken((v) => !v)}
className="absolute inset-y-0 right-2 flex items-center text-gray-500 hover:text-gray-700"
tabIndex={-1}
>
{showAuthToken ? <EyeOff size={16} /> : <Eye size={16} />}
</button>
</div>
</div>
<div>
<label className="block text-sm font-medium">Twilio Phone Number</label>
<input
type="text"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
className="mt-1 p-2 border rounded w-full font-mono text-sm"
placeholder="+1xxxxxxxxxx"
required
/>
<p className="text-xs text-gray-500 mt-1">Must be in E.164 format, e.g. +16175551234</p>
</div>
<div>
<label className="block text-sm font-medium">Voicemail Greeting</label>
<textarea
value={greetingMessage}
onChange={(e) => setGreetingMessage(e.target.value)}
className="mt-1 p-2 border rounded w-full text-sm resize-none"
rows={3}
placeholder="Thank you for calling. Please leave a message after the beep and we will get back to you shortly."
/>
<p className="text-xs text-gray-500 mt-1">This message plays when a patient calls your Twilio number. Leave blank to use the default.</p>
</div>
<div className="flex items-center gap-3 pt-1">
<button
type="submit"
className="bg-teal-600 text-white px-4 py-2 rounded hover:bg-teal-700 text-sm"
disabled={saveMutation.isPending}
>
{saveMutation.isPending ? "Saving..." : "Save Twilio Settings"}
</button>
</div>
{isConfigured && (
<div className="mt-2 p-3 bg-gray-50 rounded border text-xs text-gray-600 space-y-1">
<p className="font-medium text-gray-700">Twilio Webhook URLs</p>
<p>SMS: <code className="bg-white border px-1 rounded">https://communitydentistsoflowell.mydentalofficemanagement.com/api/twilio/webhook/sms</code></p>
<p>Voice: <code className="bg-white border px-1 rounded">https://communitydentistsoflowell.mydentalofficemanagement.com/api/twilio/webhook/voice</code></p>
<p className="text-gray-400">Set these in your Twilio Console Phone Numbers your number</p>
</div>
)}
</form>
)}
</CardContent>
</Card>
);
}