feat: improve backup management, settings UI, and Twilio webhooks

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Gitead
2026-05-04 00:52:42 -04:00
parent 5689269690
commit 79e20b693d
13 changed files with 468 additions and 545 deletions

View File

@@ -12,8 +12,9 @@ const restoreUpload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 500 * 1024 * 1024 }, // 500 MB
fileFilter: (_req, file, cb) => {
if (file.originalname.toLowerCase().endsWith(".sql")) cb(null, true);
else cb(new Error("Only .sql files are allowed"));
const name = file.originalname.toLowerCase();
if (name.endsWith(".sql") || name.endsWith(".zip")) cb(null, true);
else cb(new Error("Only .sql or .zip files are allowed"));
},
});
@@ -339,13 +340,21 @@ router.post("/restore", restoreUpload.single("file"), async (req: Request, res:
if (!req.file) return res.status(400).json({ error: "No file provided" });
const isZip = req.file.originalname.toLowerCase().endsWith(".zip");
// For zip files, write to a temp file so unzip can read it
let tmpZipPath: string | null = null;
if (isZip) {
tmpZipPath = path.join(os.tmpdir(), `restore_${Date.now()}.zip`);
fs.writeFileSync(tmpZipPath, req.file.buffer);
}
// Drop and recreate the public schema so existing tables don't block the restore.
// pg_dump without --clean produces no DROP statements, so restoring into an
// existing schema would silently skip CREATE TABLE / fail on duplicate inserts.
try {
await prisma.$executeRawUnsafe(`DROP SCHEMA public CASCADE`);
await prisma.$executeRawUnsafe(`CREATE SCHEMA public`);
} catch (err: any) {
if (tmpZipPath) try { fs.unlinkSync(tmpZipPath); } catch {}
console.error("Failed to reset schema before restore:", err);
return res.status(500).json({ error: "Failed to reset database schema", details: err.message });
}
@@ -366,30 +375,41 @@ router.post("/restore", restoreUpload.single("file"), async (req: Request, res:
psql.stderr.on("data", (d) => (stderr += d.toString()));
psql.on("error", (err) => {
if (tmpZipPath) try { fs.unlinkSync(tmpZipPath); } catch {}
console.error("Failed to start psql:", err);
if (!res.headersSent)
res.status(500).json({ error: "Failed to run psql", details: err.message });
});
psql.on("close", async (code) => {
if (tmpZipPath) try { fs.unlinkSync(tmpZipPath); } catch {}
if (code !== 0) {
console.error("psql restore failed:", stderr);
return res.status(500).json({ error: "Restore failed", details: stderr });
}
// Disconnect so Prisma drops its pooled connections and reconnects fresh
// on the next request, avoiding stale prepared statements against the old schema.
try {
await prisma.$disconnect();
} catch (_) {
// non-fatal — the restore succeeded
}
} catch (_) {}
res.json({ success: true });
});
psql.stdin.write(req.file.buffer);
psql.stdin.end();
if (isZip && tmpZipPath) {
// Pipe the first .sql entry from the zip directly into psql stdin
const unzip = spawn("unzip", ["-p", tmpZipPath, "*.sql"]);
let unzipErr = "";
unzip.stderr.on("data", (d) => (unzipErr += d.toString()));
unzip.on("error", (err) => {
if (tmpZipPath) try { fs.unlinkSync(tmpZipPath); } catch {}
if (!res.headersSent)
res.status(500).json({ error: "Failed to extract zip", details: err.message });
});
unzip.stdout.pipe(psql.stdin);
} else {
psql.stdin.write(req.file.buffer);
psql.stdin.end();
}
});
export default router;

View File

@@ -25,6 +25,7 @@ import paymentsReportsRoutes from "./payments-reports";
import exportPaymentsReportsRoutes from "./export-payments-reports";
import jobMonitorRoutes from "./job-monitor";
import twilioRoutes from "./twilio";
import aiSettingsRoutes from "./ai-settings";
const router = Router();
@@ -54,5 +55,6 @@ router.use("/payments-reports", paymentsReportsRoutes);
router.use("/export-payments-reports", exportPaymentsReportsRoutes);
router.use("/job-monitor", jobMonitorRoutes);
router.use("/twilio", twilioRoutes);
router.use("/ai", aiSettingsRoutes);
export default router;

View File

@@ -1,6 +1,7 @@
import express, { Request, Response } from "express";
import { storage } from "../storage";
import { prisma as db } from "@repo/db/client";
import { runReminderGraph } from "../ai/reminder-graph";
const router = express.Router();
@@ -10,12 +11,13 @@ router.post("/webhook/sms", async (req: Request, res: Response): Promise<any> =>
const { From, Body, MessageSid } = req.body;
const normalizedFrom = (From || "").replace(/\D/g, "");
const allPatients = await db.patient.findMany({ select: { id: true, phone: true } });
const allPatients = await db.patient.findMany({ select: { id: true, phone: true, userId: true } });
const patient = allPatients.find(
(p: { id: number; phone: string | null }) => p.phone && p.phone.replace(/\D/g, "") === normalizedFrom
(p: { id: number; phone: string | null; userId: number }) => p.phone && p.phone.replace(/\D/g, "") === normalizedFrom
);
if (patient) {
// Save the inbound message
await storage.createCommunication({
patientId: patient.id,
channel: "sms",
@@ -24,6 +26,28 @@ router.post("/webhook/sms", async (req: Request, res: Response): Promise<any> =>
body: Body,
twilioSid: MessageSid,
});
// Run AI graph if API key is configured
const aiSettings = await storage.getAiSettings(patient.userId);
if (aiSettings?.apiKey) {
const { reply, intent } = await runReminderGraph(Body, aiSettings.apiKey);
if (reply) {
// Save the AI outbound reply
await storage.createCommunication({
patientId: patient.id,
channel: "sms",
direction: "outbound",
status: "sent",
body: reply,
});
res.set("Content-Type", "text/xml");
return res.send(
`<?xml version="1.0" encoding="UTF-8"?><Response><Message>${escapeXml(reply)}</Message></Response>`
);
}
}
}
res.set("Content-Type", "text/xml");
@@ -104,4 +128,13 @@ router.post("/webhook/voice-recording", async (req: Request, res: Response): Pro
}
});
function escapeXml(text: string): string {
return text
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
}
export default router;