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

@@ -13,6 +13,9 @@
"license": "ISC", "license": "ISC",
"type": "commonjs", "type": "commonjs",
"dependencies": { "dependencies": {
"@google/generative-ai": "^0.24.1",
"@langchain/google-genai": "^2.1.30",
"@langchain/langgraph": "^1.2.9",
"archiver": "^7.0.1", "archiver": "^7.0.1",
"axios": "^1.9.0", "axios": "^1.9.0",
"bcrypt": "^5.1.1", "bcrypt": "^5.1.1",

View File

@@ -11,12 +11,31 @@ const LOCAL_BACKUP_DIR = path.resolve(process.cwd(), "backups");
// Name of the USB backup subfolder the user creates on their drive // Name of the USB backup subfolder the user creates on their drive
const USB_BACKUP_FOLDER_NAME = "USB Backup"; const USB_BACKUP_FOLDER_NAME = "USB Backup";
const MAX_BACKUPS = 30;
function ensureLocalBackupDir() { function ensureLocalBackupDir() {
if (!fs.existsSync(LOCAL_BACKUP_DIR)) { if (!fs.existsSync(LOCAL_BACKUP_DIR)) {
fs.mkdirSync(LOCAL_BACKUP_DIR, { recursive: true }); fs.mkdirSync(LOCAL_BACKUP_DIR, { recursive: true });
} }
} }
function pruneOldBackups(dir: string) {
try {
const files = fs.readdirSync(dir)
.filter((f) => f.endsWith(".sql") || f.endsWith(".zip"))
.map((f) => ({ name: f, mtime: fs.statSync(path.join(dir, f)).mtimeMs }))
.sort((a, b) => b.mtime - a.mtime);
const toDelete = files.slice(MAX_BACKUPS);
for (const file of toDelete) {
fs.unlinkSync(path.join(dir, file.name));
console.log(`🗑️ Pruned old backup: ${file.name}`);
}
} catch (err) {
console.warn("Failed to prune old backups:", err);
}
}
async function getAdminUser() { async function getAdminUser() {
const batchSize = 100; const batchSize = 100;
let offset = 0; let offset = 0;
@@ -49,6 +68,7 @@ export const startBackupCron = () => {
const startedAt = new Date(); const startedAt = new Date();
const log = await cronJobLogStorage.createJobLog("local-backup", startedAt); const log = await cronJobLogStorage.createJobLog("local-backup", startedAt);
await cronJobLogStorage.completeJobLog(log.id, "skipped", new Date()); await cronJobLogStorage.completeJobLog(log.id, "skipped", new Date());
await storage.deleteNotificationsByType(admin.id, "BACKUP");
return; return;
} }
@@ -58,6 +78,7 @@ export const startBackupCron = () => {
try { try {
const filename = `dental_backup_${Date.now()}.sql`; const filename = `dental_backup_${Date.now()}.sql`;
await backupDatabaseToPath({ destinationPath: LOCAL_BACKUP_DIR, filename }); await backupDatabaseToPath({ destinationPath: LOCAL_BACKUP_DIR, filename });
pruneOldBackups(LOCAL_BACKUP_DIR);
await storage.createBackup(admin.id); await storage.createBackup(admin.id);
await storage.deleteNotificationsByType(admin.id, "BACKUP"); await storage.deleteNotificationsByType(admin.id, "BACKUP");
await cronJobLogStorage.completeJobLog(log.id, "success", new Date()); await cronJobLogStorage.completeJobLog(log.id, "success", new Date());
@@ -93,6 +114,7 @@ export const startBackupCron = () => {
const startedAt = new Date(); const startedAt = new Date();
const log = await cronJobLogStorage.createJobLog("usb-backup", startedAt); const log = await cronJobLogStorage.createJobLog("usb-backup", startedAt);
await cronJobLogStorage.completeJobLog(log.id, "skipped", new Date()); await cronJobLogStorage.completeJobLog(log.id, "skipped", new Date());
await storage.deleteNotificationsByType(admin.id, "BACKUP");
return; return;
} }
@@ -131,6 +153,7 @@ export const startBackupCron = () => {
try { try {
const filename = `dental_backup_usb_${Date.now()}.sql`; const filename = `dental_backup_usb_${Date.now()}.sql`;
await backupDatabaseToPath({ destinationPath: usbBackupPath, filename }); await backupDatabaseToPath({ destinationPath: usbBackupPath, filename });
pruneOldBackups(usbBackupPath);
await storage.createBackup(admin.id); await storage.createBackup(admin.id);
await storage.deleteNotificationsByType(admin.id, "BACKUP"); await storage.deleteNotificationsByType(admin.id, "BACKUP");
await cronJobLogStorage.completeJobLog(log.id, "success", new Date()); await cronJobLogStorage.completeJobLog(log.id, "success", new Date());

View File

@@ -12,8 +12,9 @@ const restoreUpload = multer({
storage: multer.memoryStorage(), storage: multer.memoryStorage(),
limits: { fileSize: 500 * 1024 * 1024 }, // 500 MB limits: { fileSize: 500 * 1024 * 1024 }, // 500 MB
fileFilter: (_req, file, cb) => { fileFilter: (_req, file, cb) => {
if (file.originalname.toLowerCase().endsWith(".sql")) cb(null, true); const name = file.originalname.toLowerCase();
else cb(new Error("Only .sql files are allowed")); 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" }); 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. // 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 { try {
await prisma.$executeRawUnsafe(`DROP SCHEMA public CASCADE`); await prisma.$executeRawUnsafe(`DROP SCHEMA public CASCADE`);
await prisma.$executeRawUnsafe(`CREATE SCHEMA public`); await prisma.$executeRawUnsafe(`CREATE SCHEMA public`);
} catch (err: any) { } catch (err: any) {
if (tmpZipPath) try { fs.unlinkSync(tmpZipPath); } catch {}
console.error("Failed to reset schema before restore:", err); console.error("Failed to reset schema before restore:", err);
return res.status(500).json({ error: "Failed to reset database schema", details: err.message }); 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.stderr.on("data", (d) => (stderr += d.toString()));
psql.on("error", (err) => { psql.on("error", (err) => {
if (tmpZipPath) try { fs.unlinkSync(tmpZipPath); } catch {}
console.error("Failed to start psql:", err); console.error("Failed to start psql:", err);
if (!res.headersSent) if (!res.headersSent)
res.status(500).json({ error: "Failed to run psql", details: err.message }); res.status(500).json({ error: "Failed to run psql", details: err.message });
}); });
psql.on("close", async (code) => { psql.on("close", async (code) => {
if (tmpZipPath) try { fs.unlinkSync(tmpZipPath); } catch {}
if (code !== 0) { if (code !== 0) {
console.error("psql restore failed:", stderr); console.error("psql restore failed:", stderr);
return res.status(500).json({ error: "Restore failed", details: 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 { try {
await prisma.$disconnect(); await prisma.$disconnect();
} catch (_) { } catch (_) {}
// non-fatal — the restore succeeded
}
res.json({ success: true }); res.json({ success: true });
}); });
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.write(req.file.buffer);
psql.stdin.end(); psql.stdin.end();
}
}); });
export default router; export default router;

View File

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

View File

@@ -1,6 +1,7 @@
import express, { Request, Response } from "express"; import express, { Request, Response } from "express";
import { storage } from "../storage"; import { storage } from "../storage";
import { prisma as db } from "@repo/db/client"; import { prisma as db } from "@repo/db/client";
import { runReminderGraph } from "../ai/reminder-graph";
const router = express.Router(); 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 { From, Body, MessageSid } = req.body;
const normalizedFrom = (From || "").replace(/\D/g, ""); 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( 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) { if (patient) {
// Save the inbound message
await storage.createCommunication({ await storage.createCommunication({
patientId: patient.id, patientId: patient.id,
channel: "sms", channel: "sms",
@@ -24,6 +26,28 @@ router.post("/webhook/sms", async (req: Request, res: Response): Promise<any> =>
body: Body, body: Body,
twilioSid: MessageSid, 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"); 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; export default router;

View File

@@ -1,54 +1,73 @@
import { spawn } from "child_process"; import { spawn } from "child_process";
import fs from "fs";
import path from "path";
import archiver from "archiver";
interface BackupToPathParams { interface BackupToPathParams {
destinationPath: string; destinationPath: string;
filename: string; filename: string; // should end in .zip
} }
export async function backupDatabaseToPath({ export async function backupDatabaseToPath({
destinationPath, destinationPath,
filename, filename,
}: BackupToPathParams): Promise<void> { }: BackupToPathParams): Promise<void> {
const path = await import("path"); // Verify write access before spawning pg_dump
const fs = await import("fs"); try {
fs.accessSync(destinationPath, fs.constants.W_OK);
} catch {
throw new Error(
`No write permission to "${destinationPath}". Try running: sudo chmod a+w "${destinationPath}"`
);
}
const outputFile = path.join(destinationPath, filename); const zipFile = path.join(destinationPath, filename);
const sqlName = filename.replace(/\.zip$/, ".sql");
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const output = fs.createWriteStream(zipFile);
const archive = archiver("zip", { zlib: { level: 6 } });
output.on("close", () => resolve());
archive.on("error", (err) => {
try { if (fs.existsSync(zipFile)) fs.unlinkSync(zipFile); } catch {}
reject(err);
});
archive.pipe(output);
const pgDump = spawn( const pgDump = spawn(
"pg_dump", "pg_dump",
[ [
"--no-acl", "--no-acl",
"--no-owner", "--no-owner",
"-h", "-h", process.env.DB_HOST || "localhost",
process.env.DB_HOST || "localhost", "-U", process.env.DB_USER || "postgres",
"-U",
process.env.DB_USER || "postgres",
"-f",
outputFile,
process.env.DB_NAME || "dental_db", process.env.DB_NAME || "dental_db",
], ],
{ {
env: { env: { ...process.env, PGPASSWORD: process.env.DB_PASSWORD },
...process.env,
PGPASSWORD: process.env.DB_PASSWORD,
},
} }
); );
let pgError = ""; let pgError = "";
pgDump.stderr.on("data", (d) => (pgError += d.toString())); pgDump.stderr.on("data", (d) => (pgError += d.toString()));
pgDump.on("error", (err) => {
try { if (fs.existsSync(zipFile)) fs.unlinkSync(zipFile); } catch {}
reject(new Error(`Failed to start pg_dump: ${err.message}. Make sure postgresql-client is installed.`));
});
pgDump.on("close", (code) => { pgDump.on("close", (code) => {
if (code !== 0) { if (code !== 0) {
// clean up partial file if it was created try { if (fs.existsSync(zipFile)) fs.unlinkSync(zipFile); } catch {}
try { reject(new Error(pgError.trim() || `pg_dump exited with code ${code}`));
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile); return;
} catch {}
return reject(new Error(pgError || "pg_dump failed"));
} }
resolve(); archive.finalize();
}); });
// Stream pg_dump stdout directly into the zip as a .sql entry
archive.append(pgDump.stdout, { name: sqlName });
}); });
} }

View File

@@ -18,6 +18,7 @@ import { patientDocumentsStorage } from './patientDocuments-storage';
import * as exportPaymentsReportsStorage from "./export-payments-reports-storage"; import * as exportPaymentsReportsStorage from "./export-payments-reports-storage";
import { cronJobLogStorage } from "./cron-job-log-storage"; import { cronJobLogStorage } from "./cron-job-log-storage";
import { twilioStorage } from "./twilio-storage"; import { twilioStorage } from "./twilio-storage";
import { aiSettingsStorage } from "./ai-settings-storage";
export const storage = { export const storage = {
@@ -39,6 +40,7 @@ export const storage = {
...exportPaymentsReportsStorage, ...exportPaymentsReportsStorage,
...cronJobLogStorage, ...cronJobLogStorage,
...twilioStorage, ...twilioStorage,
...aiSettingsStorage,
}; };

View File

@@ -45,6 +45,7 @@ function Router() {
<ProtectedRoute path="/patients" component={() => <PatientsPage />} /> <ProtectedRoute path="/patients" component={() => <PatientsPage />} />
<ProtectedRoute path="/chart/:section" component={() => <ChartPage />} /> <ProtectedRoute path="/chart/:section" component={() => <ChartPage />} />
<ProtectedRoute path="/chart" component={() => <ChartPage />} /> <ProtectedRoute path="/chart" component={() => <ChartPage />} />
<ProtectedRoute path="/settings/:section" component={() => <SettingsPage />} adminOnly />
<ProtectedRoute path="/settings" component={() => <SettingsPage />} adminOnly /> <ProtectedRoute path="/settings" component={() => <SettingsPage />} adminOnly />
<ProtectedRoute path="/claims" component={() => <ClaimsPage />} /> <ProtectedRoute path="/claims" component={() => <ClaimsPage />} />
<ProtectedRoute <ProtectedRoute

View File

@@ -105,7 +105,10 @@ export function BackupDestinationManager() {
const backupNowMutation = useMutation({ const backupNowMutation = useMutation({
mutationFn: async () => { mutationFn: async () => {
const res = await apiRequest("POST", "/api/database-management/backup-path"); const res = await apiRequest("POST", "/api/database-management/backup-path");
if (!res.ok) throw new Error((await res.json()).error || "Backup failed"); if (!res.ok) {
const body = await res.json();
throw new Error(body.details || body.error || "Backup failed");
}
return res.json(); return res.json();
}, },
onSuccess: (data) => { onSuccess: (data) => {

View File

@@ -25,7 +25,7 @@ interface FolderBrowserModalProps {
export function FolderBrowserModal({ open, onClose, onSelect }: FolderBrowserModalProps) { export function FolderBrowserModal({ open, onClose, onSelect }: FolderBrowserModalProps) {
const [browsePath, setBrowsePath] = useState("/"); const [browsePath, setBrowsePath] = useState("/");
const [selected, setSelected] = useState<string | null>(null); const [selected, setSelected] = useState<string>("/");
const { data, isLoading, isError } = useQuery<BrowseResult>({ const { data, isLoading, isError } = useQuery<BrowseResult>({
queryKey: ["/db/browse", browsePath], queryKey: ["/db/browse", browsePath],
@@ -41,15 +41,13 @@ export function FolderBrowserModal({ open, onClose, onSelect }: FolderBrowserMod
}); });
const handleNavigate = (path: string) => { const handleNavigate = (path: string) => {
setSelected(null); setSelected(path);
setBrowsePath(path); setBrowsePath(path);
}; };
const handleConfirm = () => { const handleConfirm = () => {
if (selected) {
onSelect(selected); onSelect(selected);
onClose(); onClose();
}
}; };
return ( return (
@@ -120,7 +118,7 @@ export function FolderBrowserModal({ open, onClose, onSelect }: FolderBrowserMod
<Button variant="outline" onClick={onClose}> <Button variant="outline" onClick={onClose}>
Cancel Cancel
</Button> </Button>
<Button onClick={handleConfirm} disabled={!selected}> <Button onClick={handleConfirm}>
Select Folder Select Folder
</Button> </Button>
</DialogFooter> </DialogFooter>

View File

@@ -82,7 +82,7 @@ export function ImportDatabaseSection() {
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<p className="text-sm text-gray-500"> <p className="text-sm text-gray-500">
Restore the database from a <span className="font-medium text-gray-700">.sql</span> backup file. Restore the database from a <span className="font-medium text-gray-700">.sql</span> or <span className="font-medium text-gray-700">.zip</span> backup file.
This will overwrite all existing data. This will overwrite all existing data.
</p> </p>
@@ -90,7 +90,7 @@ export function ImportDatabaseSection() {
<input <input
ref={fileInputRef} ref={fileInputRef}
type="file" type="file"
accept=".sql" accept=".sql,.zip"
onChange={handleFileChange} onChange={handleFileChange}
className="block text-sm text-gray-600 file:mr-3 file:py-1.5 file:px-3 file:rounded file:border file:border-gray-300 file:text-sm file:bg-white file:text-gray-700 hover:file:bg-gray-50 cursor-pointer" className="block text-sm text-gray-600 file:mr-3 file:py-1.5 file:px-3 file:rounded file:border file:border-gray-300 file:text-sm file:bg-white file:text-gray-700 hover:file:bg-gray-50 cursor-pointer"
/> />

View File

@@ -20,6 +20,12 @@ import {
Microscope, Microscope,
ChevronDown, ChevronDown,
ChevronRight, ChevronRight,
UserCog,
User,
ShieldCheck,
Stethoscope,
Workflow,
Bot,
} from "lucide-react"; } from "lucide-react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useMemo, useState, useEffect } from "react"; import { useMemo, useState, useEffect } from "react";
@@ -30,6 +36,8 @@ type NavChild = {
name: string; name: string;
path: string; path: string;
icon: React.ReactNode; icon: React.ReactNode;
adminOnly?: boolean;
groupLabel?: string; // renders a group heading before this item
}; };
type NavItem = { type NavItem = {
@@ -42,13 +50,14 @@ type NavItem = {
export function Sidebar() { export function Sidebar() {
const [location] = useLocation(); const [location] = useLocation();
const { state, openMobile, setOpenMobile } = useSidebar(); // "expanded" | "collapsed" const { state, openMobile, setOpenMobile } = useSidebar();
const { user } = useAuth(); const { user } = useAuth();
const isAdmin = user?.username === "admin"; const isAdmin = user?.username === "admin";
const [expandedPaths, setExpandedPaths] = useState<Set<string>>(() => { const [expandedPaths, setExpandedPaths] = useState<Set<string>>(() => {
const s = new Set<string>(); const s = new Set<string>();
if (location.startsWith("/chart")) s.add("/chart"); if (location.startsWith("/chart")) s.add("/chart");
if (location.startsWith("/settings")) s.add("/settings");
return s; return s;
}); });
@@ -56,6 +65,9 @@ export function Sidebar() {
if (location.startsWith("/chart")) { if (location.startsWith("/chart")) {
setExpandedPaths((prev) => new Set([...prev, "/chart"])); setExpandedPaths((prev) => new Set([...prev, "/chart"]));
} }
if (location.startsWith("/settings")) {
setExpandedPaths((prev) => new Set([...prev, "/settings"]));
}
}, [location]); }, [location]);
const togglePath = (path: string) => { const togglePath = (path: string) => {
@@ -163,6 +175,53 @@ export function Sidebar() {
path: "/settings", path: "/settings",
icon: <Settings className="h-5 w-5 text-gray-400" />, icon: <Settings className="h-5 w-5 text-gray-400" />,
adminOnly: true, adminOnly: true,
children: [
// ── General ──────────────────────────────────────────
{
groupLabel: "General",
name: "Staff Management",
path: "/settings/staff",
icon: <Users className="h-4 w-4 text-gray-400" />,
},
{
name: "Manage Users",
path: "/settings/users",
icon: <UserCog className="h-4 w-4 text-gray-400" />,
adminOnly: true,
},
{
name: "Account Settings",
path: "/settings/account",
icon: <User className="h-4 w-4 text-gray-400" />,
},
{
name: "Insurance Credentials",
path: "/settings/credentials",
icon: <ShieldCheck className="h-4 w-4 text-gray-400" />,
},
{
name: "NPI Providers",
path: "/settings/npi",
icon: <Stethoscope className="h-4 w-4 text-gray-400" />,
},
{
name: "Program Bridge",
path: "/settings/programs",
icon: <Workflow className="h-4 w-4 text-gray-400" />,
},
// ── Advanced ─────────────────────────────────────────
{
groupLabel: "Advanced",
name: "Twilio Settings",
path: "/settings/twilio",
icon: <Phone className="h-4 w-4 text-gray-400" />,
},
{
name: "Google AI Settings",
path: "/settings/ai",
icon: <Bot className="h-4 w-4 text-gray-400" />,
},
],
}, },
], ],
[] []
@@ -172,16 +231,16 @@ export function Sidebar() {
<div <div
className={cn( className={cn(
"bg-white border-r border-gray-200 shadow-sm z-20", "bg-white border-r border-gray-200 shadow-sm z-20",
"overflow-hidden will-change-[width]", "overflow-x-hidden will-change-[width]",
"transition-[width] duration-200 ease-in-out", "transition-[width] duration-200 ease-in-out",
openMobile openMobile
? "fixed top-16 left-0 h-[calc(100vh-4rem)] w-64 block md:hidden" ? "fixed top-16 left-0 h-[calc(100vh-4rem)] w-64 block md:hidden"
: "hidden md:block", : "hidden md:block",
"md:static md:top-auto md:h-auto md:flex-shrink-0", "md:static md:top-auto md:h-full md:flex-shrink-0",
state === "collapsed" ? "md:w-0 overflow-hidden" : "md:w-64" state === "collapsed" ? "md:w-0 overflow-hidden" : "md:w-64"
)} )}
> >
<div className="p-2"> <div className="p-2 h-full overflow-y-auto">
<nav role="navigation" aria-label="Main"> <nav role="navigation" aria-label="Main">
{navItems {navItems
.filter((item) => !item.adminOnly || isAdmin) .filter((item) => !item.adminOnly || isAdmin)
@@ -189,6 +248,9 @@ export function Sidebar() {
if (item.children) { if (item.children) {
const isParentActive = location.startsWith(item.path); const isParentActive = location.startsWith(item.path);
const isExpanded = expandedPaths.has(item.path); const isExpanded = expandedPaths.has(item.path);
const visibleChildren = item.children.filter(
(c) => !c.adminOnly || isAdmin
);
return ( return (
<div key={item.path}> <div key={item.path}>
@@ -214,12 +276,19 @@ export function Sidebar() {
{isExpanded && ( {isExpanded && (
<div className="ml-4 border-l border-gray-200 pl-2 mb-1"> <div className="ml-4 border-l border-gray-200 pl-2 mb-1">
{item.children.map((child) => { {visibleChildren.map((child) => {
const isActive = location === child.path || location.startsWith(child.path + "/"); const isActive =
location === child.path ||
location.startsWith(child.path + "/");
return ( return (
<div key={child.path}>
{child.groupLabel && (
<p className="text-[10px] font-semibold uppercase tracking-wider text-gray-400 px-2 pt-2 pb-0.5">
{child.groupLabel}
</p>
)}
<Link <Link
to={child.path} to={child.path}
key={child.path}
onClick={() => setOpenMobile(false)} onClick={() => setOpenMobile(false)}
> >
<div <div
@@ -236,6 +305,7 @@ export function Sidebar() {
</span> </span>
</div> </div>
</Link> </Link>
</div>
); );
})} })}
</div> </div>
@@ -256,7 +326,6 @@ export function Sidebar() {
)} )}
> >
{item.icon} {item.icon}
{/* show label only after expand animation completes */}
<span className="whitespace-nowrap select-none"> <span className="whitespace-nowrap select-none">
{item.name} {item.name}
</span> </span>

View File

@@ -1,6 +1,7 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import { Eye, EyeOff } from "lucide-react"; import { Eye, EyeOff } from "lucide-react";
import { useQuery, useMutation } from "@tanstack/react-query"; import { useQuery, useMutation } from "@tanstack/react-query";
import { useParams } from "wouter";
import { StaffTable } from "@/components/staffs/staff-table"; import { StaffTable } from "@/components/staffs/staff-table";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { Card, CardContent } from "@/components/ui/card"; import { Card, CardContent } from "@/components/ui/card";
@@ -13,524 +14,273 @@ import { Staff } from "@repo/db/types";
import { NpiProviderTable } from "@/components/settings/npiProviderTable"; import { NpiProviderTable } from "@/components/settings/npiProviderTable";
import { ProgramBridgeTable } from "@/components/settings/program-bridge-table"; import { ProgramBridgeTable } from "@/components/settings/program-bridge-table";
import { TwilioSettingsCard } from "@/components/settings/twilio-settings-card"; import { TwilioSettingsCard } from "@/components/settings/twilio-settings-card";
import { AiSettingsCard } from "@/components/settings/ai-settings-card";
type SectionId =
| "staff"
| "users"
| "account"
| "credentials"
| "npi"
| "programs"
| "twilio"
| "ai";
export default function SettingsPage() { export default function SettingsPage() {
const { toast } = useToast(); const { toast } = useToast();
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); const { user: currentUser } = useAuth();
const isAdmin = currentUser?.username === "admin";
// Modal and editing staff state const params = useParams<{ section?: string }>();
const section = (params.section as SectionId | undefined) ?? "staff";
// Staff state
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
const [credentialModalOpen, setCredentialModalOpen] = useState(false);
const [editingStaff, setEditingStaff] = useState<Staff | null>(null); const [editingStaff, setEditingStaff] = useState<Staff | null>(null);
const toggleMobileMenu = () => setIsMobileMenuOpen((prev) => !prev);
// Fetch staff data
const {
data: staff = [],
isLoading,
isError,
error,
} = useQuery<Staff[]>({
queryKey: ["/api/staffs/"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/staffs/");
if (!res.ok) {
throw new Error("Failed to fetch staff");
}
return res.json();
},
staleTime: 1000 * 60 * 5, // 5 minutes cache
});
// Add Staff mutation
const addStaffMutate = useMutation<
Staff, // Return type
Error, // Error type
Omit<Staff, "id" | "userId" | "createdAt"> // Variables
>({
mutationFn: async (newStaff: Omit<Staff, "id" | "userId" | "createdAt">) => {
const res = await apiRequest("POST", "/api/staffs/", newStaff);
if (!res.ok) {
const errorData = await res.json().catch(() => null);
throw new Error(errorData?.message || "Failed to add staff");
}
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/staffs/"] });
toast({
title: "Staff Added",
description: "Staff member added successfully.",
variant: "default",
});
},
onError: (error: any) => {
toast({
title: "Error",
description: error?.message || "Failed to add staff",
variant: "destructive",
});
},
});
// Update Staff mutation
const updateStaffMutate = useMutation<
Staff,
Error,
{ id: number; updatedFields: Partial<Staff> }
>({
mutationFn: async ({
id,
updatedFields,
}: {
id: number;
updatedFields: Partial<Staff>;
}) => {
const res = await apiRequest("PUT", `/api/staffs/${id}`, updatedFields);
if (!res.ok) {
const errorData = await res.json().catch(() => null);
throw new Error(errorData?.message || "Failed to update staff");
}
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/staffs/"] });
toast({
title: "Staff Updated",
description: "Staff member updated successfully.",
variant: "default",
});
},
onError: (error: any) => {
toast({
title: "Error",
description: error?.message || "Failed to update staff",
variant: "destructive",
});
},
});
// Delete Staff mutation
const deleteStaffMutation = useMutation<number, Error, number>({
mutationFn: async (id: number) => {
const res = await apiRequest("DELETE", `/api/staffs/${id}`);
if (!res.ok) {
const errorData = await res.json().catch(() => null);
throw new Error(errorData?.message || "Failed to delete staff");
}
return id;
},
onSuccess: () => {
setIsDeleteStaffOpen(false);
queryClient.invalidateQueries({ queryKey: ["/api/staffs/"] });
toast({
title: "Staff Removed",
description: "Staff member deleted.",
variant: "default",
});
},
onError: (error: any) => {
toast({
title: "Error",
description: error?.message || "Failed to delete staff",
variant: "destructive",
});
},
});
// Extract mutation states for modal control and loading
const isAdding = addStaffMutate.status === "pending";
const isAddSuccess = addStaffMutate.status === "success";
const isUpdating = updateStaffMutate.status === "pending";
const isUpdateSuccess = updateStaffMutate.status === "success";
// Open Add modal
const openAddStaffModal = () => {
setEditingStaff(null);
setModalOpen(true);
};
// Open Edit modal
const openEditStaffModal = (staff: Staff) => {
setEditingStaff(staff);
setModalOpen(true);
};
// Handle form submit for Add or Edit
const handleFormSubmit = (formData: Omit<Staff, "id" | "userId" | "createdAt">) => {
if (editingStaff) {
// Editing existing staff
if (editingStaff.id === undefined) {
toast({
title: "Error",
description: "Staff ID is missing",
variant: "destructive",
});
return;
}
updateStaffMutate.mutate({
id: editingStaff.id,
updatedFields: formData,
});
} else {
addStaffMutate.mutate(formData);
}
};
const handleModalCancel = () => {
setModalOpen(false);
};
// Close modal on successful add/update
useEffect(() => {
if (isAddSuccess || isUpdateSuccess) {
setModalOpen(false);
}
}, [isAddSuccess, isUpdateSuccess]);
const [isDeleteStaffOpen, setIsDeleteStaffOpen] = useState(false); const [isDeleteStaffOpen, setIsDeleteStaffOpen] = useState(false);
const [currentStaff, setCurrentStaff] = useState<Staff | undefined>( const [currentStaff, setCurrentStaff] = useState<Staff | undefined>(undefined);
undefined,
);
const handleDeleteStaff = (staff: Staff) => { // User management state
setCurrentStaff(staff);
setIsDeleteStaffOpen(true);
};
const handleConfirmDeleteStaff = async () => {
if (currentStaff?.id) {
deleteStaffMutation.mutate(currentStaff.id);
} else {
toast({
title: "Error",
description: "No Staff selected for deletion.",
variant: "destructive",
});
}
};
const handleViewStaff = (staff: Staff) =>
alert(
`Viewing staff member:\n${staff.name} (${staff.email || "No email"})`,
);
// MANAGE USERS (admin only)
const [newUsername, setNewUsername] = useState(""); const [newUsername, setNewUsername] = useState("");
const [newPassword, setNewPassword] = useState(""); const [newPassword, setNewPassword] = useState("");
const [showNewUserPassword, setShowNewUserPassword] = useState(false); const [showNewUserPassword, setShowNewUserPassword] = useState(false);
const [showAdminPassword, setShowAdminPassword] = useState(false); const [showAdminPassword, setShowAdminPassword] = useState(false);
const [usernameUser, setUsernameUser] = useState("");
const {
data: allUsers = [],
refetch: refetchUsers,
} = useQuery<{ id: number; username: string }[]>({
queryKey: ["/api/users/list"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/users/list");
if (!res.ok) return [];
return res.json();
},
enabled: false, // loaded lazily below
});
const { user: currentUser } = useAuth();
const isAdmin = currentUser?.username === "admin";
useEffect(() => { useEffect(() => {
if (isAdmin) refetchUsers(); if (currentUser?.username) setUsernameUser(currentUser.username);
}, [isAdmin]); }, [currentUser]);
// ── Staff ──────────────────────────────────────────────────────
const { data: staff = [], isLoading: staffLoading, isError: staffError, error: staffErrorMsg } = useQuery<Staff[]>({
queryKey: ["/api/staffs/"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/staffs/");
if (!res.ok) throw new Error("Failed to fetch staff");
return res.json();
},
staleTime: 1000 * 60 * 5,
});
const addStaffMutate = useMutation<Staff, Error, Omit<Staff, "id" | "userId" | "createdAt">>({
mutationFn: async (newStaff) => {
const res = await apiRequest("POST", "/api/staffs/", newStaff);
if (!res.ok) { const e = await res.json().catch(() => null); throw new Error(e?.message || "Failed to add staff"); }
return res.json();
},
onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["/api/staffs/"] }); toast({ title: "Staff Added" }); },
onError: (e: any) => toast({ title: "Error", description: e?.message, variant: "destructive" }),
});
const updateStaffMutate = useMutation<Staff, Error, { id: number; updatedFields: Partial<Staff> }>({
mutationFn: async ({ id, updatedFields }) => {
const res = await apiRequest("PUT", `/api/staffs/${id}`, updatedFields);
if (!res.ok) { const e = await res.json().catch(() => null); throw new Error(e?.message || "Failed to update staff"); }
return res.json();
},
onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["/api/staffs/"] }); toast({ title: "Staff Updated" }); },
onError: (e: any) => toast({ title: "Error", description: e?.message, variant: "destructive" }),
});
const deleteStaffMutation = useMutation<number, Error, number>({
mutationFn: async (id) => {
const res = await apiRequest("DELETE", `/api/staffs/${id}`);
if (!res.ok) { const e = await res.json().catch(() => null); throw new Error(e?.message || "Failed to delete staff"); }
return id;
},
onSuccess: () => { setIsDeleteStaffOpen(false); queryClient.invalidateQueries({ queryKey: ["/api/staffs/"] }); toast({ title: "Staff Removed" }); },
onError: (e: any) => toast({ title: "Error", description: e?.message, variant: "destructive" }),
});
useEffect(() => {
if (addStaffMutate.status === "success" || updateStaffMutate.status === "success") setModalOpen(false);
}, [addStaffMutate.status, updateStaffMutate.status]);
// ── Users ──────────────────────────────────────────────────────
const { data: allUsers = [], refetch: refetchUsers } = useQuery<{ id: number; username: string }[]>({
queryKey: ["/api/users/list"],
queryFn: async () => { const res = await apiRequest("GET", "/api/users/list"); if (!res.ok) return []; return res.json(); },
enabled: false,
});
useEffect(() => { if (isAdmin) refetchUsers(); }, [isAdmin]);
const addUserMutation = useMutation({ const addUserMutation = useMutation({
mutationFn: async (data: { username: string; password: string }) => { mutationFn: async (data: { username: string; password: string }) => {
const res = await apiRequest("POST", "/api/users/", data); const res = await apiRequest("POST", "/api/users/", data);
if (!res.ok) { if (!res.ok) { const e = await res.json().catch(() => null); throw new Error(e?.error || "Failed to create user"); }
const err = await res.json().catch(() => null);
throw new Error(err?.error || "Failed to create user");
}
return res.json(); return res.json();
}, },
onSuccess: () => { onSuccess: () => { setNewUsername(""); setNewPassword(""); refetchUsers(); toast({ title: "User Created" }); },
setNewUsername(""); onError: (e: any) => toast({ title: "Error", description: e?.message, variant: "destructive" }),
setNewPassword("");
refetchUsers();
toast({ title: "User Created", description: "New user added successfully." });
},
onError: (err: any) => {
toast({ title: "Error", description: err?.message || "Failed to create user", variant: "destructive" });
},
}); });
const deleteUserMutation = useMutation({ const deleteUserMutation = useMutation({
mutationFn: async (id: number) => { mutationFn: async (id: number) => { const res = await apiRequest("DELETE", `/api/users/${id}`); if (!res.ok) throw new Error("Failed to delete user"); },
const res = await apiRequest("DELETE", `/api/users/${id}`); onSuccess: () => { refetchUsers(); toast({ title: "User Deleted" }); },
if (!res.ok) throw new Error("Failed to delete user"); onError: (e: any) => toast({ title: "Error", description: e?.message, variant: "destructive" }),
},
onSuccess: () => {
refetchUsers();
toast({ title: "User Deleted", description: "User removed successfully." });
},
onError: (err: any) => {
toast({ title: "Error", description: err?.message || "Failed to delete user", variant: "destructive" });
},
}); });
// MANAGE USER (own account)
const [usernameUser, setUsernameUser] = useState("");
useEffect(() => {
if (currentUser?.username) {
setUsernameUser(currentUser.username);
}
}, [currentUser]);
//update user mutation
const updateUserMutate = useMutation({ const updateUserMutate = useMutation({
mutationFn: async ( mutationFn: async (updates: Partial<{ username: string; password: string }>) => {
updates: Partial<{ username: string; password: string }>,
) => {
if (!currentUser?.id) throw new Error("User not loaded"); if (!currentUser?.id) throw new Error("User not loaded");
const res = await apiRequest("PUT", `/api/users/${currentUser.id}`, updates); const res = await apiRequest("PUT", `/api/users/${currentUser.id}`, updates);
if (!res.ok) { if (!res.ok) { const e = await res.json().catch(() => null); throw new Error(e?.error || "Failed to update user"); }
const errorData = await res.json().catch(() => null);
throw new Error(errorData?.error || "Failed to update user");
}
return res.json(); return res.json();
}, },
onSuccess: () => { onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["/api/users/"] }); toast({ title: "Updated", description: "Your profile has been updated." }); },
queryClient.invalidateQueries({ queryKey: ["/api/users/"] }); onError: (e: any) => toast({ title: "Error", description: e?.message, variant: "destructive" }),
toast({
title: "Updated",
description: "Your profile has been updated.",
variant: "default",
});
},
onError: (err: any) => {
toast({
title: "Error",
description: err?.message || "Failed to update user",
variant: "destructive",
});
},
}); });
// ── Section renderer ───────────────────────────────────────────
const renderSection = () => {
switch (section) {
case "staff":
return ( return (
<div>
<Card> <Card>
<CardContent> <CardContent>
<div className="mt-8"> <div className="mt-4">
<StaffTable <StaffTable
staff={staff} staff={staff}
isLoading={isLoading} isLoading={staffLoading}
isError={isError} isError={staffError}
onAdd={openAddStaffModal} onAdd={() => { setEditingStaff(null); setModalOpen(true); }}
onEdit={openEditStaffModal} onEdit={(s) => { setEditingStaff(s); setModalOpen(true); }}
onDelete={handleDeleteStaff} onDelete={(s) => { setCurrentStaff(s); setIsDeleteStaffOpen(true); }}
onView={handleViewStaff} onView={(s) => alert(`Viewing staff member:\n${s.name} (${s.email || "No email"})`)}
/> />
{isError && ( {staffError && <p className="mt-4 text-red-600">{(staffErrorMsg as Error)?.message || "Failed to load staff data."}</p>}
<p className="mt-4 text-red-600">
{(error as Error)?.message || "Failed to load staff data."}
</p>
)}
<DeleteConfirmationDialog <DeleteConfirmationDialog
isOpen={isDeleteStaffOpen} isOpen={isDeleteStaffOpen}
onConfirm={handleConfirmDeleteStaff} onConfirm={() => { if (currentStaff?.id) deleteStaffMutation.mutate(currentStaff.id); }}
onCancel={() => setIsDeleteStaffOpen(false)} onCancel={() => setIsDeleteStaffOpen(false)}
entityName={currentStaff?.name} entityName={currentStaff?.name}
/> />
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
);
{/* Modal Overlay */} case "users":
{modalOpen && ( return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-50"> <Card>
<div className="bg-white rounded-lg p-6 w-full max-w-md shadow-lg">
<h2 className="text-lg font-bold mb-4">
{editingStaff ? "Edit Staff" : "Add Staff"}
</h2>
<StaffForm
initialData={editingStaff || undefined}
onSubmit={handleFormSubmit}
onCancel={handleModalCancel}
isLoading={isAdding || isUpdating}
/>
</div>
</div>
)}
{/* Manage Users section (admin only) */}
{isAdmin && (
<Card className="mt-6">
<CardContent className="space-y-4 py-6"> <CardContent className="space-y-4 py-6">
<h3 className="text-lg font-semibold">Manage Users</h3> <h3 className="text-lg font-semibold">Manage Users</h3>
{/* Existing users list */}
<div className="border rounded divide-y"> <div className="border rounded divide-y">
{allUsers.length === 0 && ( {allUsers.length === 0 && <p className="text-sm text-gray-500 p-3">No users found.</p>}
<p className="text-sm text-gray-500 p-3">No users found.</p>
)}
{allUsers.map((u) => ( {allUsers.map((u) => (
<div key={u.id} className="flex items-center justify-between px-3 py-2"> <div key={u.id} className="flex items-center justify-between px-3 py-2">
<span className="text-sm font-medium">{u.username}</span> <span className="text-sm font-medium">{u.username}</span>
{u.username !== "admin" && ( {u.username !== "admin" && (
<button <button className="text-sm text-red-600 hover:underline" onClick={() => deleteUserMutation.mutate(u.id)} disabled={deleteUserMutation.isPending}>
className="text-sm text-red-600 hover:underline"
onClick={() => deleteUserMutation.mutate(u.id)}
disabled={deleteUserMutation.isPending}
>
Delete Delete
</button> </button>
)} )}
</div> </div>
))} ))}
</div> </div>
<form className="space-y-3 pt-2" onSubmit={(e) => { e.preventDefault(); if (!newUsername.trim() || !newPassword.trim()) return; addUserMutation.mutate({ username: newUsername.trim(), password: newPassword.trim() }); }}>
{/* Add new user form */} <h4 className="text-sm font-semibold text-gray-700">Add New User</h4>
<form
className="space-y-3 pt-2"
onSubmit={(e) => {
e.preventDefault();
if (!newUsername.trim() || !newPassword.trim()) return;
addUserMutation.mutate({ username: newUsername.trim(), password: newPassword.trim() });
}}
>
<h4 className="text-sm font-semibold text-gray-700">Add New Users</h4>
<div> <div>
<label className="block text-sm font-medium">Username</label> <label className="block text-sm font-medium">Username</label>
<input <input type="text" value={newUsername} onChange={(e) => setNewUsername(e.target.value)} className="mt-1 p-2 border rounded w-full" placeholder="Enter username" required />
type="text"
value={newUsername}
onChange={(e) => setNewUsername(e.target.value)}
className="mt-1 p-2 border rounded w-full"
placeholder="Enter username"
required
/>
</div> </div>
<div> <div>
<label className="block text-sm font-medium">Password</label> <label className="block text-sm font-medium">Password</label>
<div className="relative mt-1"> <div className="relative mt-1">
<input <input type={showNewUserPassword ? "text" : "password"} value={newPassword} onChange={(e) => setNewPassword(e.target.value)} className="p-2 border rounded w-full pr-10" placeholder="••••••••" required />
type={showNewUserPassword ? "text" : "password"} <button type="button" onClick={() => setShowNewUserPassword((v) => !v)} className="absolute inset-y-0 right-2 flex items-center text-gray-500 hover:text-gray-700" tabIndex={-1}>
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="p-2 border rounded w-full pr-10"
placeholder="••••••••"
required
/>
<button
type="button"
onClick={() => setShowNewUserPassword((v) => !v)}
className="absolute inset-y-0 right-2 flex items-center text-gray-500 hover:text-gray-700"
tabIndex={-1}
>
{showNewUserPassword ? <EyeOff size={16} /> : <Eye size={16} />} {showNewUserPassword ? <EyeOff size={16} /> : <Eye size={16} />}
</button> </button>
</div> </div>
</div> </div>
<button <button type="submit" className="bg-teal-600 text-white px-4 py-2 rounded hover:bg-teal-700" disabled={addUserMutation.isPending}>
type="submit" {addUserMutation.isPending ? "Adding..." : "Add User"}
className="bg-teal-600 text-white px-4 py-2 rounded hover:bg-teal-700"
disabled={addUserMutation.isPending}
>
{addUserMutation.isPending ? "Adding..." : "Add"}
</button> </button>
</form> </form>
</CardContent> </CardContent>
</Card> </Card>
)} );
{/* User Setting section */} case "account":
<Card className="mt-6"> return (
<Card>
<CardContent className="space-y-4 py-6"> <CardContent className="space-y-4 py-6">
<h3 className="text-lg font-semibold">Admin Settings</h3> <h3 className="text-lg font-semibold">Account Settings</h3>
<form <form className="space-y-4" onSubmit={(e) => {
className="space-y-4"
onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
const formData = new FormData(e.currentTarget); const formData = new FormData(e.currentTarget);
const password = const password = formData.get("password")?.toString().trim() || undefined;
formData.get("password")?.toString().trim() || undefined; updateUserMutate.mutate({ ...(isAdmin ? {} : { username: usernameUser?.trim() || undefined }), password: password || undefined });
}}>
updateUserMutate.mutate({
...(isAdmin ? {} : { username: usernameUser?.trim() || undefined }),
password: password || undefined,
});
}}
>
<div> <div>
<label className="block text-sm font-medium">Username</label> <label className="block text-sm font-medium">Username</label>
<input <input type="text" name="username" value={usernameUser} onChange={(e) => setUsernameUser(e.target.value)} className="mt-1 p-2 border rounded w-full disabled:bg-gray-100 disabled:cursor-not-allowed disabled:text-gray-500" disabled={isAdmin} />
type="text" {isAdmin && <p className="text-xs text-gray-500 mt-1">Admin username cannot be changed.</p>}
name="username"
value={usernameUser}
onChange={(e) => setUsernameUser(e.target.value)}
className="mt-1 p-2 border rounded w-full disabled:bg-gray-100 disabled:cursor-not-allowed disabled:text-gray-500"
disabled={isAdmin}
/>
{isAdmin && (
<p className="text-xs text-gray-500 mt-1">Admin username cannot be changed.</p>
)}
</div> </div>
<div> <div>
<label className="block text-sm font-medium">New Password</label> <label className="block text-sm font-medium">New Password</label>
<div className="relative mt-1"> <div className="relative mt-1">
<input <input type={showAdminPassword ? "text" : "password"} name="password" className="p-2 border rounded w-full pr-10" placeholder="••••••••" />
type={showAdminPassword ? "text" : "password"} <button type="button" onClick={() => setShowAdminPassword((v) => !v)} className="absolute inset-y-0 right-2 flex items-center text-gray-500 hover:text-gray-700" tabIndex={-1}>
name="password"
className="p-2 border rounded w-full pr-10"
placeholder="••••••••"
/>
<button
type="button"
onClick={() => setShowAdminPassword((v) => !v)}
className="absolute inset-y-0 right-2 flex items-center text-gray-500 hover:text-gray-700"
tabIndex={-1}
>
{showAdminPassword ? <EyeOff size={16} /> : <Eye size={16} />} {showAdminPassword ? <EyeOff size={16} /> : <Eye size={16} />}
</button> </button>
</div> </div>
<p className="text-xs text-gray-500 mt-1"> <p className="text-xs text-gray-500 mt-1">Leave blank to keep current password.</p>
Leave blank to keep current password.
</p>
</div> </div>
<button type="submit" className="bg-teal-600 text-white px-4 py-2 rounded hover:bg-teal-700" disabled={updateUserMutate.isPending}>
<button
type="submit"
className="bg-teal-600 text-white px-4 py-2 rounded hover:bg-teal-700"
disabled={updateUserMutate.isPending}
>
{updateUserMutate.isPending ? "Saving..." : "Save Changes"} {updateUserMutate.isPending ? "Saving..." : "Save Changes"}
</button> </button>
</form> </form>
</CardContent> </CardContent>
</Card> </Card>
);
{/* Twilio Section */} case "credentials":
<div className="mt-6"> return <CredentialTable />;
<TwilioSettingsCard />
</div>
{/* Credential Section */} case "npi":
<div className="mt-6"> return <NpiProviderTable />;
<CredentialTable />
</div>
{/* NpiProvider Section */} case "programs":
<div className="mt-6"> return <ProgramBridgeTable />;
<NpiProviderTable />
</div>
{/* Program Bridge Section */} case "twilio":
<div className="mt-6"> return <TwilioSettingsCard />;
<ProgramBridgeTable />
case "ai":
return <AiSettingsCard />;
default:
return null;
}
};
return (
<>
{renderSection()}
{/* Staff add/edit modal */}
{modalOpen && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-50">
<div className="bg-white rounded-lg p-6 w-full max-w-md shadow-lg">
<h2 className="text-lg font-bold mb-4">{editingStaff ? "Edit Staff" : "Add Staff"}</h2>
<StaffForm
initialData={editingStaff || undefined}
onSubmit={(formData) => {
if (editingStaff) {
if (!editingStaff.id) return;
updateStaffMutate.mutate({ id: editingStaff.id, updatedFields: formData });
} else {
addStaffMutate.mutate(formData);
}
}}
onCancel={() => setModalOpen(false)}
isLoading={addStaffMutate.status === "pending" || updateStaffMutate.status === "pending"}
/>
</div> </div>
</div> </div>
)}
</>
); );
} }