feat: migrate SMS/voice to Telnyx (TeXML), keep browser dial pad on Twilio

Twilio now handles only the in-browser dial pad (Access Token + browser-Device
outbound TwiML); Telnyx takes over SMS, inbound voicemail, the AI voice
conversation loop, and staff-triggered outbound calls via TeXML. Adds
TelnyxSettings model, Communication.provider discriminator, new comms/routes
modules, and a real Telnyx Settings page.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-03 15:39:43 -04:00
co-authored by Claude Sonnet 5
parent b899659e13
commit 79ac6aaa31
463 changed files with 7823 additions and 3397 deletions
@@ -305,6 +305,11 @@ export function Sidebar() {
path: "/settings/twilio",
icon: <Phone className="h-4 w-4 text-gray-400" />,
},
{
name: "Telnyx Settings",
path: "/settings/telnyx",
icon: <Phone className="h-4 w-4 text-gray-400" />,
},
{
name: "AI API Setting",
path: "/settings/ai",
@@ -269,9 +269,9 @@ export function MessageThread({ patient, onBack, appointmentInfo }: MessageThrea
const [pendingStartFlow, setPendingStartFlow] = useState<"new_patient" | "reschedule" | null>(null);
useQuery<{ enabled: boolean }>({
queryKey: ["/api/twilio/ai-handoff", patient.id],
queryKey: ["/api/telnyx/ai-handoff", patient.id],
queryFn: async () => {
const res = await apiRequest("GET", `/api/twilio/ai-handoff/${patient.id}`);
const res = await apiRequest("GET", `/api/telnyx/ai-handoff/${patient.id}`);
return res.json();
},
onSuccess: (data: { enabled: boolean }) => setHandOffToAI(data.enabled),
@@ -289,7 +289,7 @@ export function MessageThread({ patient, onBack, appointmentInfo }: MessageThrea
const handoffMutation = useMutation({
mutationFn: async (enabled: boolean) =>
apiRequest("PUT", `/api/twilio/ai-handoff/${patient.id}`, { enabled }),
apiRequest("PUT", `/api/telnyx/ai-handoff/${patient.id}`, { enabled }),
});
const handleHandoffToggle = (enabled: boolean) => {
@@ -318,7 +318,7 @@ export function MessageThread({ patient, onBack, appointmentInfo }: MessageThrea
const sendMessageMutation = useMutation({
mutationFn: async (message: string) =>
apiRequest("POST", "/api/twilio/send-sms", {
apiRequest("POST", "/api/telnyx/send-sms", {
to: patient.phone,
message,
patientId: patient.id,
@@ -78,7 +78,7 @@ export function SmsTemplateDialog({
const { toast } = useToast();
const { data: savedTemplates = {} } = useQuery<Record<string, string>>({
queryKey: ["/api/twilio/templates"],
queryKey: ["/api/telnyx/templates"],
enabled: open,
});
@@ -99,7 +99,7 @@ export function SmsTemplateDialog({
const sendMutation = useMutation({
mutationFn: async (message: string) => {
return apiRequest("POST", "/api/twilio/send-sms", {
return apiRequest("POST", "/api/telnyx/send-sms", {
to: patient!.phone,
message,
patientId: patient!.id,
@@ -112,16 +112,16 @@ export function SmsTemplateDialog({
setMessageText("");
},
onError: (err: any) => {
toast({ title: "Failed to Send SMS", description: err.message || "Please check your Twilio configuration.", variant: "destructive" });
toast({ title: "Failed to Send SMS", description: err.message || "Please check your Telnyx configuration.", variant: "destructive" });
},
});
const updateMutation = useMutation({
mutationFn: async ({ key, body }: { key: string; body: string }) => {
return apiRequest("PUT", `/api/twilio/templates/${key}`, { body });
return apiRequest("PUT", `/api/telnyx/templates/${key}`, { body });
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/twilio/templates"] });
queryClient.invalidateQueries({ queryKey: ["/api/telnyx/templates"] });
toast({ title: "Template Updated", description: "This template will be used going forward." });
},
onError: (err: any) => {
@@ -1107,9 +1107,9 @@ export function AiChatSettingsCard() {
});
const { data: smsTemplateListData, isLoading: smsLoading } = useQuery<SmsTemplate[]>({
queryKey: ["/api/twilio/sms-template-list"],
queryKey: ["/api/telnyx/sms-template-list"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/twilio/sms-template-list");
const res = await apiRequest("GET", "/api/telnyx/sms-template-list");
if (!res.ok) return [];
return res.json();
},
@@ -1200,7 +1200,7 @@ export function AiChatSettingsCard() {
const saveSmsListMutation = useMutation({
mutationFn: async (list: SmsTemplate[]) => {
const res = await apiRequest("PUT", "/api/twilio/sms-template-list", list);
const res = await apiRequest("PUT", "/api/telnyx/sms-template-list", list);
if (!res.ok) {
const err = await res.json().catch(() => null);
throw new Error(err?.message || "Failed to save SMS templates");
@@ -1208,7 +1208,7 @@ export function AiChatSettingsCard() {
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/twilio/sms-template-list"] });
queryClient.invalidateQueries({ queryKey: ["/api/telnyx/sms-template-list"] });
toast({ title: "SMS template saved" });
},
onError: (err: any) => {
@@ -1382,7 +1382,7 @@ export function AiChatSettingsCard() {
<code className="bg-muted px-1 py-0.5 rounded text-xs font-mono">{"{officeName}"}</code>{" "}
<code className="bg-muted px-1 py-0.5 rounded text-xs font-mono">{"{officeAddress}"}</code>{" "}
<code className="bg-muted px-1 py-0.5 rounded text-xs font-mono" title="Office call-in phone number">{"{officePhone}"}</code>{" "}
<code className="bg-muted px-1 py-0.5 rounded text-xs font-mono" title="Twilio SMS number patients text back to">{"{twilioPhone}"}</code>{" "}
<code className="bg-muted px-1 py-0.5 rounded text-xs font-mono" title="SMS number patients text back to">{"{twilioPhone}"}</code>{" "}
<code className="bg-muted px-1 py-0.5 rounded text-xs font-mono">{"{appointmentDate}"}</code>{" "}
<code className="bg-muted px-1 py-0.5 rounded text-xs font-mono">{"{appointmentTime}"}</code>
</p>
@@ -0,0 +1,227 @@
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 TelnyxSettings = {
id?: number;
apiKey: string;
accountSid?: string | null;
phoneNumber: string;
texmlApplicationId?: string | null;
messagingProfileId?: string | null;
webhookPublicKey?: string | null;
greetingMessage?: string | null;
};
export function TelnyxSettingsCard() {
const { toast } = useToast();
const [apiKey, setApiKey] = useState("");
const [accountSid, setAccountSid] = useState("");
const [phoneNumber, setPhoneNumber] = useState("");
const [texmlApplicationId, setTexmlApplicationId] = useState("");
const [messagingProfileId, setMessagingProfileId] = useState("");
const [webhookPublicKey, setWebhookPublicKey] = useState("");
const [greetingMessage, setGreetingMessage] = useState("");
const [showApiKey, setShowApiKey] = useState(false);
const { data: settings, isLoading } = useQuery<TelnyxSettings | null>({
queryKey: ["/api/telnyx/settings"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/telnyx/settings");
if (!res.ok) return null;
return res.json();
},
});
useEffect(() => {
if (settings) {
setApiKey(settings.apiKey ?? "");
setAccountSid(settings.accountSid ?? "");
setPhoneNumber(settings.phoneNumber ?? "");
setTexmlApplicationId(settings.texmlApplicationId ?? "");
setMessagingProfileId(settings.messagingProfileId ?? "");
setWebhookPublicKey(settings.webhookPublicKey ?? "");
setGreetingMessage(settings.greetingMessage ?? "");
}
}, [settings]);
const saveMutation = useMutation({
mutationFn: async (data: TelnyxSettings) => {
const res = await apiRequest("PUT", "/api/telnyx/settings", data);
if (!res.ok) {
const err = await res.json().catch(() => null);
throw new Error(err?.message || "Failed to save Telnyx settings");
}
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/telnyx/settings"] });
toast({ title: "Telnyx Settings Saved", description: "Your Telnyx 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 (!apiKey.trim() || !phoneNumber.trim()) return;
saveMutation.mutate({
apiKey: apiKey.trim(),
accountSid: accountSid.trim() || null,
phoneNumber: phoneNumber.trim(),
texmlApplicationId: texmlApplicationId.trim() || null,
messagingProfileId: messagingProfileId.trim() || null,
webhookPublicKey: webhookPublicKey.trim() || null,
greetingMessage: greetingMessage.trim() || null,
});
};
const isConfigured = !!(settings?.apiKey && settings?.phoneNumber);
const webhookOrigin = typeof window !== "undefined" ? window.location.origin : "";
return (
<Card>
<CardContent className="space-y-4 py-6">
<div className="flex items-center gap-2">
<h3 className="text-lg font-semibold">Telnyx 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">
Telnyx handles SMS, voicemail, and AI phone calls — everything except the in-browser dial pad
(see Twilio Settings above). Find these in your{" "}
<span className="font-medium">Telnyx Mission Control Portal</span>.
</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">API Key</label>
<div className="relative mt-1">
<input
type={showApiKey ? "text" : "password"}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
className="p-2 border rounded w-full pr-10 font-mono text-sm"
placeholder="KEYxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
required
/>
<button
type="button"
onClick={() => setShowApiKey((v) => !v)}
className="absolute inset-y-0 right-2 flex items-center text-gray-500 hover:text-gray-700"
tabIndex={-1}
>
{showApiKey ? <EyeOff size={16} /> : <Eye size={16} />}
</button>
</div>
</div>
<div>
<label className="block text-sm font-medium">Account SID <span className="text-gray-400 font-normal">(for placing calls)</span></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="Mission Control Portal → Account SID"
/>
<p className="text-xs text-gray-500 mt-1">Separate from the API Key — required for outbound/AI calls.</p>
</div>
<div>
<label className="block text-sm font-medium">Telnyx 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">TeXML Application ID <span className="text-gray-400 font-normal">(for calls)</span></label>
<input
type="text"
value={texmlApplicationId}
onChange={(e) => setTexmlApplicationId(e.target.value)}
className="mt-1 p-2 border rounded w-full font-mono text-sm"
placeholder="TeXML Application ID"
/>
<p className="text-xs text-gray-500 mt-1">
In the Telnyx portal → Voice → TeXML Applications → create one → set the Voice webhook URL to{" "}
<code className="bg-gray-100 px-1 rounded text-xs">{webhookOrigin}/api/telnyx/webhook/voice</code>
{" "}then paste the Application ID here.
</p>
</div>
<div>
<label className="block text-sm font-medium">Messaging Profile ID <span className="text-gray-400 font-normal">(optional)</span></label>
<input
type="text"
value={messagingProfileId}
onChange={(e) => setMessagingProfileId(e.target.value)}
className="mt-1 p-2 border rounded w-full font-mono text-sm"
placeholder="Messaging Profile ID"
/>
</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 Telnyx number. Leave blank to use the default.</p>
</div>
<div>
<label className="block text-sm font-medium">Webhook Public Key <span className="text-gray-400 font-normal">(for signature verification)</span></label>
<input
type="text"
value={webhookPublicKey}
onChange={(e) => setWebhookPublicKey(e.target.value)}
className="mt-1 p-2 border rounded w-full font-mono text-sm"
placeholder="Public key from Telnyx portal → Webhooks"
/>
</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 Telnyx 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">Telnyx Webhook URLs</p>
<p>SMS: <code className="bg-white border px-1 rounded">{webhookOrigin}/api/telnyx/webhook/sms</code></p>
<p>Voice: <code className="bg-white border px-1 rounded">{webhookOrigin}/api/telnyx/webhook/voice</code></p>
<p className="text-gray-400">Set SMS on your Messaging Profile, and Voice on your TeXML Application, in the Telnyx portal.</p>
</div>
)}
</form>
)}
</CardContent>
</Card>
);
}
@@ -10,7 +10,6 @@ type TwilioSettings = {
accountSid: string;
authToken: string;
phoneNumber: string;
greetingMessage?: string | null;
twimlAppSid?: string | null;
};
@@ -19,7 +18,6 @@ export function TwilioSettingsCard() {
const [accountSid, setAccountSid] = useState("");
const [authToken, setAuthToken] = useState("");
const [phoneNumber, setPhoneNumber] = useState("");
const [greetingMessage, setGreetingMessage] = useState("");
const [twimlAppSid, setTwimlAppSid] = useState("");
const [showAuthToken, setShowAuthToken] = useState(false);
@@ -37,7 +35,6 @@ export function TwilioSettingsCard() {
setAccountSid(settings.accountSid ?? "");
setAuthToken(settings.authToken ?? "");
setPhoneNumber(settings.phoneNumber ?? "");
setGreetingMessage(settings.greetingMessage ?? "");
setTwimlAppSid(settings.twimlAppSid ?? "");
}
}, [settings]);
@@ -63,10 +60,11 @@ export function TwilioSettingsCard() {
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, twimlAppSid: twimlAppSid.trim() || null });
saveMutation.mutate({ accountSid: accountSid.trim(), authToken: authToken.trim(), phoneNumber: phoneNumber.trim(), twimlAppSid: twimlAppSid.trim() || null });
};
const isConfigured = !!(settings?.accountSid && settings?.authToken && settings?.phoneNumber);
const webhookOrigin = typeof window !== "undefined" ? window.location.origin : "";
return (
<Card>
@@ -80,7 +78,8 @@ export function TwilioSettingsCard() {
)}
</div>
<p className="text-sm text-gray-500">
Enter your Twilio credentials to enable SMS and calling features. Find these in your{" "}
Twilio powers the in-browser dial pad only — SMS, voicemail, and AI calls run through{" "}
<span className="font-medium">Telnyx</span> (see Telnyx Settings below). Find these credentials in your{" "}
<span className="font-medium">Twilio Console</span> → Account Info.
</p>
@@ -132,19 +131,7 @@ export function TwilioSettingsCard() {
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>
<p className="text-xs text-gray-500 mt-1">Must be in E.164 format, e.g. +16175551234. Used as the caller ID for dial pad calls.</p>
</div>
<div>
@@ -158,7 +145,7 @@ export function TwilioSettingsCard() {
/>
<p className="text-xs text-gray-500 mt-1">
In Twilio Console → TwiML Apps → create one → set Voice URL to{" "}
<code className="bg-gray-100 px-1 rounded text-xs">https://communitydentistsoflowell.mydentalofficemanagement.com/api/twilio/webhook/voice-browser</code>
<code className="bg-gray-100 px-1 rounded text-xs">{webhookOrigin}/api/twilio/webhook/voice-browser</code>
{" "}then paste the App SID here. Required for the dial pad.
</p>
</div>
@@ -172,15 +159,6 @@ export function TwilioSettingsCard() {
{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>