Files
DentalManagementMH07/apps/Backend/src/storage/twilio-storage.ts
Gitead 7929dc6e19 feat: office address, multi-template SMS manager, hardcoded defaults with auto-seed
- Add streetAddress/city/state/zipCode fields to OfficeContact (schema + storage + UI)
- Support {officeAddress} variable in batch reminder SMS
- Replace single SMS template field with full CRUD template list (add/rename/edit/delete)
- Store SMS template list under _sms_template_list; first template synced to batch reminder
- Hardcode all AI chat template defaults into codebase (reminder SMS, greetings, fallback)
- Add seed-templates.ts that auto-seeds default templates for all users on server boot
- Update README: note that templates are auto-configured on first boot

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 23:18:04 -04:00

125 lines
5.1 KiB
TypeScript

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 getAiChatTemplates(userId: number): Promise<Record<string, string>> {
const settings = await db.twilioSettings.findUnique({ where: { userId } });
const all = (settings?.templates as Record<string, string>) || {};
return {
reminderGreeting: all["_ai_chat_reminder_greeting"] ?? "",
newPatientGreeting: all["_ai_chat_new_patient_greeting"] ?? "",
generalFallback: all["_ai_chat_general_fallback"] ?? "",
rescheduleGreeting: all["_ai_chat_reschedule_greeting"] ?? "",
reminderSms: all["_ai_chat_reminder_sms"] ?? "",
};
},
async saveAiChatTemplates(userId: number, templates: { reminderGreeting?: string; newPatientGreeting?: string; generalFallback?: string; rescheduleGreeting?: string; reminderSms?: string }) {
const settings = await db.twilioSettings.findUnique({ where: { userId } });
const existing = (settings?.templates as Record<string, string>) || {};
const updated: Record<string, string> = { ...existing };
if (templates.reminderGreeting !== undefined) updated["_ai_chat_reminder_greeting"] = templates.reminderGreeting;
if (templates.newPatientGreeting !== undefined) updated["_ai_chat_new_patient_greeting"] = templates.newPatientGreeting;
if (templates.generalFallback !== undefined) updated["_ai_chat_general_fallback"] = templates.generalFallback;
if (templates.rescheduleGreeting !== undefined) updated["_ai_chat_reschedule_greeting"] = templates.rescheduleGreeting;
if (templates.reminderSms !== undefined) updated["_ai_chat_reminder_sms"] = templates.reminderSms;
return db.twilioSettings.upsert({
where: { userId },
update: { templates: updated },
create: { userId, accountSid: "", authToken: "", phoneNumber: "", templates: updated },
});
},
async getSmsTemplateList(userId: number): Promise<{ id: string; name: string; body: string }[]> {
const settings = await db.twilioSettings.findUnique({ where: { userId } });
const all = (settings?.templates as Record<string, string>) || {};
const raw = all["_sms_template_list"];
if (!raw) return [];
try { return JSON.parse(raw); } catch { return []; }
},
async saveSmsTemplateList(userId: number, templates: { id: string; name: string; body: string }[]) {
const settings = await db.twilioSettings.findUnique({ where: { userId } });
const existing = (settings?.templates as Record<string, string>) || {};
const updated: Record<string, string> = {
...existing,
"_sms_template_list": JSON.stringify(templates),
};
// Keep _ai_chat_reminder_sms in sync with the first template for batch sends
if (templates.length > 0) updated["_ai_chat_reminder_sms"] = templates[0]!.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 } },
},
});
},
};