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

@@ -29,6 +29,7 @@
"passport-local": "^1.0.0",
"pdfkit": "^0.17.2",
"socket.io": "^4.8.1",
"twilio": "^6.0.0",
"ws": "^8.18.0",
"zod": "^3.24.2",
"zod-validation-error": "^3.4.0"

View File

@@ -4,6 +4,7 @@ import routes from "./routes";
import { errorHandler } from "./middlewares/error.middleware";
import { apiLogger } from "./middlewares/logger.middleware";
import authRoutes from "./routes/auth";
import twilioWebhookRoutes from "./routes/twilio-webhooks";
import { authenticateJWT } from "./middlewares/auth.middleware";
import dotenv from "dotenv";
import { startBackupCron } from "./cron/backupCheck";
@@ -72,6 +73,9 @@ app.use(
app.use("/uploads", express.static(path.join(process.cwd(), "uploads")));
app.use("/api/auth", authRoutes);
// Twilio webhooks are public — Twilio sends no JWT token
app.use("/api/twilio", express.urlencoded({ extended: false }), twilioWebhookRoutes);
// All other API routes require JWT
app.use("/api", authenticateJWT, routes);
app.use(errorHandler);

View File

@@ -24,6 +24,7 @@ import cloudStorageRoutes from "./cloud-storage";
import paymentsReportsRoutes from "./payments-reports";
import exportPaymentsReportsRoutes from "./export-payments-reports";
import jobMonitorRoutes from "./job-monitor";
import twilioRoutes from "./twilio";
const router = Router();
@@ -52,5 +53,6 @@ router.use("/cloud-storage", cloudStorageRoutes);
router.use("/payments-reports", paymentsReportsRoutes);
router.use("/export-payments-reports", exportPaymentsReportsRoutes);
router.use("/job-monitor", jobMonitorRoutes);
router.use("/twilio", twilioRoutes);
export default router;

View File

@@ -374,4 +374,17 @@ router.get(
}
);
// GET /api/patients/:id/communications
router.get("/:id/communications", async (req: Request, res: Response): Promise<any> => {
try {
const patientId = parseInt(req.params.id);
if (isNaN(patientId)) return res.status(400).json({ message: "Invalid patient ID" });
const communications = await storage.getCommunicationsByPatient(patientId);
return res.status(200).json(communications);
} catch (err) {
return res.status(500).json({ error: "Failed to fetch communications", details: String(err) });
}
});
export default router;

View File

@@ -0,0 +1,107 @@
import express, { Request, Response } from "express";
import { storage } from "../storage";
import { prisma as db } from "@repo/db/client";
const router = express.Router();
// POST /api/twilio/webhook/sms (Twilio posts inbound SMS here — no auth)
router.post("/webhook/sms", async (req: Request, res: Response): Promise<any> => {
try {
const { From, Body, MessageSid } = req.body;
const normalizedFrom = (From || "").replace(/\D/g, "");
const allPatients = await db.patient.findMany({ select: { id: true, phone: true } });
const patient = allPatients.find(
(p: { id: number; phone: string | null }) => p.phone && p.phone.replace(/\D/g, "") === normalizedFrom
);
if (patient) {
await storage.createCommunication({
patientId: patient.id,
channel: "sms",
direction: "inbound",
status: "delivered",
body: Body,
twilioSid: MessageSid,
});
}
res.set("Content-Type", "text/xml");
return res.send("<Response></Response>");
} catch (err) {
res.set("Content-Type", "text/xml");
return res.send("<Response></Response>");
}
});
// POST /api/twilio/webhook/voice (Twilio posts here when someone calls — no auth)
router.post("/webhook/voice", async (req: Request, res: Response): Promise<any> => {
try {
const { From, CallSid } = req.body;
const normalizedFrom = (From || "").replace(/\D/g, "");
const allPatients = await db.patient.findMany({ select: { id: true, phone: true, userId: true } });
const patient = allPatients.find(
(p: { id: number; phone: string | null; userId: number }) => p.phone && p.phone.replace(/\D/g, "") === normalizedFrom
);
let greeting = "Thank you for calling. Please leave a message after the beep and we will get back to you shortly.";
if (patient) {
const settings = await storage.getTwilioSettings(patient.userId);
if (settings?.greetingMessage?.trim()) {
greeting = settings.greetingMessage.trim();
}
}
if (patient) {
await storage.createCommunication({
patientId: patient.id,
channel: "voice",
direction: "inbound",
status: "completed",
body: "(Inbound call — voicemail below)",
twilioSid: CallSid,
});
}
const recordingCallbackUrl = `${process.env.BASE_URL || "https://communitydentistsoflowell.mydentalofficemanagement.com"}/api/twilio/webhook/voice-recording`;
const twiml = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say voice="alice">${greeting}</Say>
<Record maxLength="120" action="${recordingCallbackUrl}" transcribeCallback="${recordingCallbackUrl}" playBeep="true"/>
<Say voice="alice">We did not receive a recording. Goodbye.</Say>
</Response>`;
res.set("Content-Type", "text/xml");
return res.send(twiml);
} catch (err) {
res.set("Content-Type", "text/xml");
return res.send(`<?xml version="1.0" encoding="UTF-8"?><Response><Say>Thank you for calling. Please try again later.</Say></Response>`);
}
});
// POST /api/twilio/webhook/voice-recording (Twilio posts recording URL here — no auth)
router.post("/webhook/voice-recording", async (req: Request, res: Response): Promise<any> => {
try {
const { CallSid, RecordingUrl } = req.body;
if (RecordingUrl && CallSid) {
const comm = await db.communication.findFirst({ where: { twilioSid: CallSid } });
if (comm) {
await db.communication.update({
where: { id: comm.id },
data: { body: `Voicemail: ${RecordingUrl}.mp3` },
});
}
}
res.set("Content-Type", "text/xml");
return res.send("<Response></Response>");
} catch (err) {
res.set("Content-Type", "text/xml");
return res.send("<Response></Response>");
}
});
export default router;

View File

@@ -0,0 +1,183 @@
import express, { Request, Response } from "express";
import twilio from "twilio";
import { storage } from "../storage";
const router = express.Router();
function getTwilioClient(accountSid: string, authToken: string) {
return twilio(accountSid, authToken);
}
// GET /api/twilio/settings
router.get("/settings", async (req: Request, res: Response): Promise<any> => {
try {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ message: "Unauthorized" });
const settings = await storage.getTwilioSettings(userId);
if (!settings) return res.status(200).json(null);
return res.status(200).json({
id: settings.id,
accountSid: settings.accountSid,
authToken: settings.authToken,
phoneNumber: settings.phoneNumber,
greetingMessage: settings.greetingMessage,
});
} catch (err) {
return res.status(500).json({ error: "Failed to fetch Twilio settings", details: String(err) });
}
});
// PUT /api/twilio/settings
router.put("/settings", async (req: Request, res: Response): Promise<any> => {
try {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ message: "Unauthorized" });
const { accountSid, authToken, phoneNumber, greetingMessage } = req.body;
if (!accountSid?.trim() || !authToken?.trim() || !phoneNumber?.trim()) {
return res.status(400).json({ message: "accountSid, authToken, and phoneNumber are required" });
}
const settings = await storage.upsertTwilioSettings(userId, {
accountSid: accountSid.trim(),
authToken: authToken.trim(),
phoneNumber: phoneNumber.trim(),
greetingMessage: greetingMessage?.trim() || null,
});
return res.status(200).json({
id: settings.id,
accountSid: settings.accountSid,
authToken: settings.authToken,
phoneNumber: settings.phoneNumber,
greetingMessage: settings.greetingMessage,
});
} catch (err) {
return res.status(500).json({ error: "Failed to save Twilio settings", details: String(err) });
}
});
// POST /api/twilio/send-sms
router.post("/send-sms", async (req: Request, res: Response): Promise<any> => {
try {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ message: "Unauthorized" });
const { to, message, patientId } = req.body;
if (!to || !message) return res.status(400).json({ message: "to and message are required" });
const settings = await storage.getTwilioSettings(userId);
if (!settings) {
return res.status(400).json({ message: "Twilio is not configured. Please add your Twilio credentials in Settings." });
}
const client = getTwilioClient(settings.accountSid, settings.authToken);
const twilioMsg = await client.messages.create({
body: message,
from: settings.phoneNumber,
to,
});
if (patientId) {
await storage.createCommunication({
patientId: Number(patientId),
userId,
channel: "sms",
direction: "outbound",
status: "sent",
body: message,
twilioSid: twilioMsg.sid,
});
}
return res.status(200).json({ sid: twilioMsg.sid, status: twilioMsg.status });
} catch (err: any) {
return res.status(500).json({ error: err.message || "Failed to send SMS" });
}
});
// GET /api/twilio/templates
router.get("/templates", async (req: Request, res: Response): Promise<any> => {
try {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ message: "Unauthorized" });
const templates = await storage.getTemplates(userId);
return res.status(200).json(templates);
} catch (err) {
return res.status(500).json({ error: "Failed to fetch templates", details: String(err) });
}
});
// PUT /api/twilio/templates/:key
router.put("/templates/:key", async (req: Request, res: Response): Promise<any> => {
try {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ message: "Unauthorized" });
const { key } = req.params;
const { body } = req.body;
if (!key || !body?.trim()) return res.status(400).json({ message: "key and body are required" });
await storage.saveTemplate(userId, key, body.trim());
return res.status(200).json({ key, body: body.trim() });
} catch (err) {
return res.status(500).json({ error: "Failed to save template", details: String(err) });
}
});
// GET /api/twilio/recent-communications
router.get("/recent-communications", async (req: Request, res: Response): Promise<any> => {
try {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ message: "Unauthorized" });
const limit = Math.min(50, parseInt(req.query.limit as string) || 20);
const communications = await storage.getRecentCommunicationsByUser(userId, limit);
return res.status(200).json(communications);
} catch (err) {
return res.status(500).json({ error: "Failed to fetch recent communications", details: String(err) });
}
});
// POST /api/twilio/make-call
router.post("/make-call", async (req: Request, res: Response): Promise<any> => {
try {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ message: "Unauthorized" });
const { to, message, patientId } = req.body;
if (!to) return res.status(400).json({ message: "to is required" });
const settings = await storage.getTwilioSettings(userId);
if (!settings) {
return res.status(400).json({ message: "Twilio is not configured. Please add your Twilio credentials in Settings." });
}
const twimlMessage = message || "Hello, this is a call from your dental office.";
const twiml = `<Response><Say>${twimlMessage}</Say></Response>`;
const client = getTwilioClient(settings.accountSid, settings.authToken);
const call = await client.calls.create({
twiml,
from: settings.phoneNumber,
to,
});
if (patientId) {
await storage.createCommunication({
patientId: Number(patientId),
userId,
channel: "voice",
direction: "outbound",
status: "queued",
twilioSid: call.sid,
});
}
return res.status(200).json({ sid: call.sid, status: call.status });
} catch (err: any) {
return res.status(500).json({ error: err.message || "Failed to make call" });
}
});
export default router;

View File

@@ -17,6 +17,7 @@ import { paymentsReportsStorage } from './payments-reports-storage';
import { patientDocumentsStorage } from './patientDocuments-storage';
import * as exportPaymentsReportsStorage from "./export-payments-reports-storage";
import { cronJobLogStorage } from "./cron-job-log-storage";
import { twilioStorage } from "./twilio-storage";
export const storage = {
@@ -37,6 +38,7 @@ export const storage = {
...patientDocumentsStorage,
...exportPaymentsReportsStorage,
...cronJobLogStorage,
...twilioStorage,
};

View File

@@ -0,0 +1,72 @@
import { prisma as db } from "@repo/db/client";
export type TwilioSettingsData = {
accountSid: string;
authToken: string;
phoneNumber: string;
greetingMessage?: string | null;
};
export type CommunicationCreateData = {
patientId: number;
userId?: number;
channel: "sms" | "voice";
direction: "outbound" | "inbound";
status: "queued" | "sent" | "delivered" | "failed" | "completed" | "busy" | "no_answer";
body?: string;
callDuration?: number;
twilioSid?: string;
};
export const twilioStorage = {
async getTwilioSettings(userId: number) {
return db.twilioSettings.findUnique({ where: { userId } });
},
async upsertTwilioSettings(userId: number, data: TwilioSettingsData) {
return db.twilioSettings.upsert({
where: { userId },
update: data,
create: { userId, ...data },
});
},
async createCommunication(data: CommunicationCreateData) {
return db.communication.create({ data: data as any });
},
async getCommunicationsByPatient(patientId: number) {
return db.communication.findMany({
where: { patientId },
orderBy: { createdAt: "asc" },
});
},
async getTemplates(userId: number): Promise<Record<string, string>> {
const settings = await db.twilioSettings.findUnique({ where: { userId } });
if (!settings?.templates) return {};
return settings.templates as Record<string, string>;
},
async saveTemplate(userId: number, key: string, body: string) {
const settings = await db.twilioSettings.findUnique({ where: { userId } });
const existing = (settings?.templates as Record<string, string>) || {};
const updated = { ...existing, [key]: body };
return db.twilioSettings.upsert({
where: { userId },
update: { templates: updated },
create: { userId, accountSid: "", authToken: "", phoneNumber: "", templates: updated },
});
},
async getRecentCommunicationsByUser(userId: number, limit = 20) {
return db.communication.findMany({
where: { patient: { userId } },
orderBy: { createdAt: "desc" },
take: limit,
include: {
patient: { select: { id: true, firstName: true, lastName: true, phone: true } },
},
});
},
};

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>
);
}

View File

@@ -1,4 +1,5 @@
import { useState } from "react";
import { formatDistanceToNow, parseISO } from "date-fns";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Sidebar } from "@/components/layout/sidebar";
import { TopAppBar } from "@/components/layout/top-app-bar";
@@ -19,6 +20,7 @@ import {
User,
Search,
MessageSquare,
Send,
X,
} from "lucide-react";
import { SmsTemplateDialog } from "@/components/patient-connection/sms-template-diaog";
@@ -92,12 +94,18 @@ export default function PatientConnectionPage() {
// Handle calling patient via Twilio
const handleCall = (patient: Patient) => {
if (patient.phone) {
makeCallMutation.mutate({
to: patient.phone,
patientId: Number(patient.id),
if (!patient.phone?.trim()) {
toast({
title: "No Phone Number",
description: "This patient does not have a phone number on file.",
variant: "destructive",
});
return;
}
makeCallMutation.mutate({
to: patient.phone,
patientId: Number(patient.id),
});
};
// Handle sending SMS
@@ -118,36 +126,19 @@ export default function PatientConnectionPage() {
setSelectedPatient(null);
};
// Sample call data
const recentCalls = [
{
id: 1,
patientName: "John Bill",
phoneNumber: "(555) 123-4567",
callType: "Appointment Request",
status: "Completed",
duration: "3:45",
time: "2 hours ago",
},
{
id: 2,
patientName: "Emily Brown",
phoneNumber: "(555) 987-6543",
callType: "Insurance Question",
status: "Follow-up Required",
duration: "6:12",
time: "4 hours ago",
},
{
id: 3,
patientName: "Mike Johnson",
phoneNumber: "(555) 456-7890",
callType: "Prescription Refill",
status: "Completed",
duration: "2:30",
time: "6 hours ago",
},
];
const { data: recentCommunications = [] } = useQuery<any[]>({
queryKey: ["/api/twilio/recent-communications"],
refetchInterval: 10000,
});
// One entry per patient, keeping the most recent communication
const recentPatients = Object.values(
recentCommunications.reduce((acc: Record<number, any>, comm: any) => {
if (!comm.patient) return acc;
if (!acc[comm.patient.id]) acc[comm.patient.id] = comm;
return acc;
}, {})
);
const callStats = [
{
@@ -206,8 +197,49 @@ export default function PatientConnectionPage() {
))}
</div>
{/* Search and Actions */}
{/* Recent Calls */}
<Card className="mb-6">
<CardHeader>
<CardTitle>Recent Conversations</CardTitle>
<CardDescription>
View and manage recent patient conversations
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
{recentPatients.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">
No conversations yet.
</p>
) : (
recentPatients.map((comm: any) => (
<div
key={comm.patient.id}
className="flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50 transition-colors cursor-pointer"
onClick={() => handleOpenMessaging(comm.patient)}
>
<div className="flex items-center space-x-3">
<div className="h-9 w-9 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-sm font-semibold flex-shrink-0">
{comm.patient.firstName?.[0]}{comm.patient.lastName?.[0]}
</div>
<p className="font-medium">
{comm.patient.firstName} {comm.patient.lastName}
</p>
</div>
<p className="text-xs text-muted-foreground">
{comm.createdAt
? formatDistanceToNow(parseISO(comm.createdAt), { addSuffix: true })
: ""}
</p>
</div>
))
)}
</div>
</CardContent>
</Card>
{/* Search and Actions */}
<Card>
<CardHeader>
<CardTitle>Search Patients</CardTitle>
<CardDescription>
@@ -265,17 +297,24 @@ export default function PatientConnectionPage() {
variant="outline"
size="sm"
onClick={() => handleCall(patient)}
disabled={!patient.phone}
data-testid={`button-call-${patient.id}`}
>
<Phone className="h-4 w-4 mr-1" />
Call
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleSMS(patient)}
data-testid={`button-sms-${patient.id}`}
>
<Send className="h-4 w-4 mr-1" />
SMS
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleOpenMessaging(patient)}
disabled={!patient.phone}
data-testid={`button-chat-${patient.id}`}
>
<MessageSquare className="h-4 w-4 mr-1" />
@@ -295,57 +334,6 @@ export default function PatientConnectionPage() {
</CardContent>
</Card>
{/* Recent Calls */}
<Card>
<CardHeader>
<CardTitle>Recent Calls</CardTitle>
<CardDescription>
View and manage recent patient calls
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{recentCalls.map((call) => (
<div
key={call.id}
className="flex items-center justify-between p-4 border rounded-lg"
>
<div className="flex items-center space-x-4">
<div className="flex-shrink-0">
<Phone className="h-5 w-5 text-muted-foreground" />
</div>
<div>
<p className="font-medium">{call.patientName}</p>
<p className="text-sm text-muted-foreground">
{call.phoneNumber}
</p>
</div>
<div>
<p className="text-sm font-medium">{call.callType}</p>
<p className="text-xs text-muted-foreground">
Duration: {call.duration}
</p>
</div>
</div>
<div className="flex items-center space-x-3">
<Badge
variant={
call.status === "Completed" ? "default" : "secondary"
}
>
{call.status}
</Badge>
<p className="text-xs text-muted-foreground">{call.time}</p>
<Button variant="outline" size="sm">
<PhoneCall className="h-4 w-4" />
</Button>
</div>
</div>
))}
</div>
</CardContent>
</Card>
{/* SMS Template Dialog */}
<SmsTemplateDialog
open={isSmsDialogOpen}

View File

@@ -12,6 +12,7 @@ import { useAuth } from "@/hooks/use-auth";
import { Staff } from "@repo/db/types";
import { NpiProviderTable } from "@/components/settings/npiProviderTable";
import { ProgramBridgeTable } from "@/components/settings/program-bridge-table";
import { TwilioSettingsCard } from "@/components/settings/twilio-settings-card";
export default function SettingsPage() {
const { toast } = useToast();
@@ -511,6 +512,11 @@ export default function SettingsPage() {
</CardContent>
</Card>
{/* Twilio Section */}
<div className="mt-6">
<TwilioSettingsCard />
</div>
{/* Credential Section */}
<div className="mt-6">
<CredentialTable />

View File

@@ -0,0 +1,12 @@
CREATE TABLE "twilio_settings" (
"id" SERIAL NOT NULL,
"userId" INTEGER NOT NULL,
"accountSid" TEXT NOT NULL,
"authToken" TEXT NOT NULL,
"phoneNumber" TEXT NOT NULL,
CONSTRAINT "twilio_settings_pkey" PRIMARY KEY ("id")
);
ALTER TABLE "twilio_settings" ADD CONSTRAINT "twilio_settings_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
CREATE UNIQUE INDEX "twilio_settings_userId_key" ON "twilio_settings"("userId");

View File

@@ -0,0 +1 @@
ALTER TABLE "twilio_settings" ADD COLUMN IF NOT EXISTS "greetingMessage" TEXT;

View File

@@ -0,0 +1 @@
ALTER TABLE "twilio_settings" ADD COLUMN IF NOT EXISTS "templates" JSONB;

View File

@@ -37,6 +37,7 @@ model User {
cloudFolders CloudFolder[]
cloudFiles CloudFile[]
communications Communication[]
twilioSettings TwilioSettings?
}
model Patient {
@@ -544,3 +545,17 @@ model PatientDocument {
@@index([patientId])
@@index([uploadedAt])
}
model TwilioSettings {
id Int @id @default(autoincrement())
userId Int @unique
accountSid String
authToken String
phoneNumber String
greetingMessage String?
templates Json?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("twilio_settings")
}