feat: improve backup management, settings UI, and Twilio webhooks
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -13,6 +13,9 @@
|
||||
"license": "ISC",
|
||||
"type": "commonjs",
|
||||
"dependencies": {
|
||||
"@google/generative-ai": "^0.24.1",
|
||||
"@langchain/google-genai": "^2.1.30",
|
||||
"@langchain/langgraph": "^1.2.9",
|
||||
"archiver": "^7.0.1",
|
||||
"axios": "^1.9.0",
|
||||
"bcrypt": "^5.1.1",
|
||||
|
||||
@@ -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
|
||||
const USB_BACKUP_FOLDER_NAME = "USB Backup";
|
||||
|
||||
const MAX_BACKUPS = 30;
|
||||
|
||||
function ensureLocalBackupDir() {
|
||||
if (!fs.existsSync(LOCAL_BACKUP_DIR)) {
|
||||
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() {
|
||||
const batchSize = 100;
|
||||
let offset = 0;
|
||||
@@ -49,6 +68,7 @@ export const startBackupCron = () => {
|
||||
const startedAt = new Date();
|
||||
const log = await cronJobLogStorage.createJobLog("local-backup", startedAt);
|
||||
await cronJobLogStorage.completeJobLog(log.id, "skipped", new Date());
|
||||
await storage.deleteNotificationsByType(admin.id, "BACKUP");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -58,6 +78,7 @@ export const startBackupCron = () => {
|
||||
try {
|
||||
const filename = `dental_backup_${Date.now()}.sql`;
|
||||
await backupDatabaseToPath({ destinationPath: LOCAL_BACKUP_DIR, filename });
|
||||
pruneOldBackups(LOCAL_BACKUP_DIR);
|
||||
await storage.createBackup(admin.id);
|
||||
await storage.deleteNotificationsByType(admin.id, "BACKUP");
|
||||
await cronJobLogStorage.completeJobLog(log.id, "success", new Date());
|
||||
@@ -93,6 +114,7 @@ export const startBackupCron = () => {
|
||||
const startedAt = new Date();
|
||||
const log = await cronJobLogStorage.createJobLog("usb-backup", startedAt);
|
||||
await cronJobLogStorage.completeJobLog(log.id, "skipped", new Date());
|
||||
await storage.deleteNotificationsByType(admin.id, "BACKUP");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -131,6 +153,7 @@ export const startBackupCron = () => {
|
||||
try {
|
||||
const filename = `dental_backup_usb_${Date.now()}.sql`;
|
||||
await backupDatabaseToPath({ destinationPath: usbBackupPath, filename });
|
||||
pruneOldBackups(usbBackupPath);
|
||||
await storage.createBackup(admin.id);
|
||||
await storage.deleteNotificationsByType(admin.id, "BACKUP");
|
||||
await cronJobLogStorage.completeJobLog(log.id, "success", new Date());
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
|
||||
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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -1,54 +1,73 @@
|
||||
import { spawn } from "child_process";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import archiver from "archiver";
|
||||
|
||||
interface BackupToPathParams {
|
||||
destinationPath: string;
|
||||
filename: string;
|
||||
filename: string; // should end in .zip
|
||||
}
|
||||
|
||||
export async function backupDatabaseToPath({
|
||||
destinationPath,
|
||||
filename,
|
||||
}: BackupToPathParams): Promise<void> {
|
||||
const path = await import("path");
|
||||
const fs = await import("fs");
|
||||
// Verify write access before spawning pg_dump
|
||||
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) => {
|
||||
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(
|
||||
"pg_dump",
|
||||
[
|
||||
"--no-acl",
|
||||
"--no-owner",
|
||||
"-h",
|
||||
process.env.DB_HOST || "localhost",
|
||||
"-U",
|
||||
process.env.DB_USER || "postgres",
|
||||
"-f",
|
||||
outputFile,
|
||||
"-h", process.env.DB_HOST || "localhost",
|
||||
"-U", process.env.DB_USER || "postgres",
|
||||
process.env.DB_NAME || "dental_db",
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
PGPASSWORD: process.env.DB_PASSWORD,
|
||||
},
|
||||
env: { ...process.env, PGPASSWORD: process.env.DB_PASSWORD },
|
||||
}
|
||||
);
|
||||
|
||||
let pgError = "";
|
||||
|
||||
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) => {
|
||||
if (code !== 0) {
|
||||
// clean up partial file if it was created
|
||||
try {
|
||||
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile);
|
||||
} catch {}
|
||||
return reject(new Error(pgError || "pg_dump failed"));
|
||||
try { if (fs.existsSync(zipFile)) fs.unlinkSync(zipFile); } catch {}
|
||||
reject(new Error(pgError.trim() || `pg_dump exited with code ${code}`));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
archive.finalize();
|
||||
});
|
||||
|
||||
// Stream pg_dump stdout directly into the zip as a .sql entry
|
||||
archive.append(pgDump.stdout, { name: sqlName });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ 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";
|
||||
import { aiSettingsStorage } from "./ai-settings-storage";
|
||||
|
||||
|
||||
export const storage = {
|
||||
@@ -39,6 +40,7 @@ export const storage = {
|
||||
...exportPaymentsReportsStorage,
|
||||
...cronJobLogStorage,
|
||||
...twilioStorage,
|
||||
...aiSettingsStorage,
|
||||
|
||||
};
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ function Router() {
|
||||
<ProtectedRoute path="/patients" component={() => <PatientsPage />} />
|
||||
<ProtectedRoute path="/chart/:section" component={() => <ChartPage />} />
|
||||
<ProtectedRoute path="/chart" component={() => <ChartPage />} />
|
||||
<ProtectedRoute path="/settings/:section" component={() => <SettingsPage />} adminOnly />
|
||||
<ProtectedRoute path="/settings" component={() => <SettingsPage />} adminOnly />
|
||||
<ProtectedRoute path="/claims" component={() => <ClaimsPage />} />
|
||||
<ProtectedRoute
|
||||
|
||||
@@ -105,7 +105,10 @@ export function BackupDestinationManager() {
|
||||
const backupNowMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
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();
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
|
||||
@@ -25,7 +25,7 @@ interface FolderBrowserModalProps {
|
||||
|
||||
export function FolderBrowserModal({ open, onClose, onSelect }: FolderBrowserModalProps) {
|
||||
const [browsePath, setBrowsePath] = useState("/");
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
const [selected, setSelected] = useState<string>("/");
|
||||
|
||||
const { data, isLoading, isError } = useQuery<BrowseResult>({
|
||||
queryKey: ["/db/browse", browsePath],
|
||||
@@ -41,15 +41,13 @@ export function FolderBrowserModal({ open, onClose, onSelect }: FolderBrowserMod
|
||||
});
|
||||
|
||||
const handleNavigate = (path: string) => {
|
||||
setSelected(null);
|
||||
setSelected(path);
|
||||
setBrowsePath(path);
|
||||
};
|
||||
|
||||
const handleConfirm = () => {
|
||||
if (selected) {
|
||||
onSelect(selected);
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -120,7 +118,7 @@ export function FolderBrowserModal({ open, onClose, onSelect }: FolderBrowserMod
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleConfirm} disabled={!selected}>
|
||||
<Button onClick={handleConfirm}>
|
||||
Select Folder
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -82,7 +82,7 @@ export function ImportDatabaseSection() {
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<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.
|
||||
</p>
|
||||
|
||||
@@ -90,7 +90,7 @@ export function ImportDatabaseSection() {
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".sql"
|
||||
accept=".sql,.zip"
|
||||
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"
|
||||
/>
|
||||
|
||||
@@ -20,6 +20,12 @@ import {
|
||||
Microscope,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
UserCog,
|
||||
User,
|
||||
ShieldCheck,
|
||||
Stethoscope,
|
||||
Workflow,
|
||||
Bot,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useMemo, useState, useEffect } from "react";
|
||||
@@ -30,6 +36,8 @@ type NavChild = {
|
||||
name: string;
|
||||
path: string;
|
||||
icon: React.ReactNode;
|
||||
adminOnly?: boolean;
|
||||
groupLabel?: string; // renders a group heading before this item
|
||||
};
|
||||
|
||||
type NavItem = {
|
||||
@@ -42,13 +50,14 @@ type NavItem = {
|
||||
|
||||
export function Sidebar() {
|
||||
const [location] = useLocation();
|
||||
const { state, openMobile, setOpenMobile } = useSidebar(); // "expanded" | "collapsed"
|
||||
const { state, openMobile, setOpenMobile } = useSidebar();
|
||||
const { user } = useAuth();
|
||||
const isAdmin = user?.username === "admin";
|
||||
|
||||
const [expandedPaths, setExpandedPaths] = useState<Set<string>>(() => {
|
||||
const s = new Set<string>();
|
||||
if (location.startsWith("/chart")) s.add("/chart");
|
||||
if (location.startsWith("/settings")) s.add("/settings");
|
||||
return s;
|
||||
});
|
||||
|
||||
@@ -56,6 +65,9 @@ export function Sidebar() {
|
||||
if (location.startsWith("/chart")) {
|
||||
setExpandedPaths((prev) => new Set([...prev, "/chart"]));
|
||||
}
|
||||
if (location.startsWith("/settings")) {
|
||||
setExpandedPaths((prev) => new Set([...prev, "/settings"]));
|
||||
}
|
||||
}, [location]);
|
||||
|
||||
const togglePath = (path: string) => {
|
||||
@@ -163,6 +175,53 @@ export function Sidebar() {
|
||||
path: "/settings",
|
||||
icon: <Settings className="h-5 w-5 text-gray-400" />,
|
||||
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
|
||||
className={cn(
|
||||
"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",
|
||||
openMobile
|
||||
? "fixed top-16 left-0 h-[calc(100vh-4rem)] w-64 block md:hidden"
|
||||
: "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"
|
||||
)}
|
||||
>
|
||||
<div className="p-2">
|
||||
<div className="p-2 h-full overflow-y-auto">
|
||||
<nav role="navigation" aria-label="Main">
|
||||
{navItems
|
||||
.filter((item) => !item.adminOnly || isAdmin)
|
||||
@@ -189,6 +248,9 @@ export function Sidebar() {
|
||||
if (item.children) {
|
||||
const isParentActive = location.startsWith(item.path);
|
||||
const isExpanded = expandedPaths.has(item.path);
|
||||
const visibleChildren = item.children.filter(
|
||||
(c) => !c.adminOnly || isAdmin
|
||||
);
|
||||
|
||||
return (
|
||||
<div key={item.path}>
|
||||
@@ -214,12 +276,19 @@ export function Sidebar() {
|
||||
|
||||
{isExpanded && (
|
||||
<div className="ml-4 border-l border-gray-200 pl-2 mb-1">
|
||||
{item.children.map((child) => {
|
||||
const isActive = location === child.path || location.startsWith(child.path + "/");
|
||||
{visibleChildren.map((child) => {
|
||||
const isActive =
|
||||
location === child.path ||
|
||||
location.startsWith(child.path + "/");
|
||||
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
|
||||
to={child.path}
|
||||
key={child.path}
|
||||
onClick={() => setOpenMobile(false)}
|
||||
>
|
||||
<div
|
||||
@@ -236,6 +305,7 @@ export function Sidebar() {
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
@@ -256,7 +326,6 @@ export function Sidebar() {
|
||||
)}
|
||||
>
|
||||
{item.icon}
|
||||
{/* show label only after expand animation completes */}
|
||||
<span className="whitespace-nowrap select-none">
|
||||
{item.name}
|
||||
</span>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Eye, EyeOff } from "lucide-react";
|
||||
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||
import { useParams } from "wouter";
|
||||
import { StaffTable } from "@/components/staffs/staff-table";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
@@ -13,524 +14,273 @@ 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";
|
||||
import { AiSettingsCard } from "@/components/settings/ai-settings-card";
|
||||
|
||||
type SectionId =
|
||||
| "staff"
|
||||
| "users"
|
||||
| "account"
|
||||
| "credentials"
|
||||
| "npi"
|
||||
| "programs"
|
||||
| "twilio"
|
||||
| "ai";
|
||||
|
||||
export default function SettingsPage() {
|
||||
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 [credentialModalOpen, setCredentialModalOpen] = useState(false);
|
||||
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 [currentStaff, setCurrentStaff] = useState<Staff | undefined>(
|
||||
undefined,
|
||||
);
|
||||
const [currentStaff, setCurrentStaff] = useState<Staff | undefined>(undefined);
|
||||
|
||||
const handleDeleteStaff = (staff: Staff) => {
|
||||
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)
|
||||
// User management state
|
||||
const [newUsername, setNewUsername] = useState("");
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [showNewUserPassword, setShowNewUserPassword] = useState(false);
|
||||
const [showAdminPassword, setShowAdminPassword] = useState(false);
|
||||
|
||||
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";
|
||||
const [usernameUser, setUsernameUser] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (isAdmin) refetchUsers();
|
||||
}, [isAdmin]);
|
||||
if (currentUser?.username) setUsernameUser(currentUser.username);
|
||||
}, [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({
|
||||
mutationFn: async (data: { username: string; password: string }) => {
|
||||
const res = await apiRequest("POST", "/api/users/", data);
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => null);
|
||||
throw new Error(err?.error || "Failed to create user");
|
||||
}
|
||||
if (!res.ok) { const e = await res.json().catch(() => null); throw new Error(e?.error || "Failed to create user"); }
|
||||
return res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
setNewUsername("");
|
||||
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" });
|
||||
},
|
||||
onSuccess: () => { setNewUsername(""); setNewPassword(""); refetchUsers(); toast({ title: "User Created" }); },
|
||||
onError: (e: any) => toast({ title: "Error", description: e?.message, variant: "destructive" }),
|
||||
});
|
||||
|
||||
const deleteUserMutation = useMutation({
|
||||
mutationFn: async (id: number) => {
|
||||
const res = await apiRequest("DELETE", `/api/users/${id}`);
|
||||
if (!res.ok) throw new Error("Failed to delete user");
|
||||
},
|
||||
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" });
|
||||
},
|
||||
mutationFn: async (id: number) => { const res = await apiRequest("DELETE", `/api/users/${id}`); if (!res.ok) throw new Error("Failed to delete user"); },
|
||||
onSuccess: () => { refetchUsers(); toast({ title: "User Deleted" }); },
|
||||
onError: (e: any) => toast({ title: "Error", description: e?.message, variant: "destructive" }),
|
||||
});
|
||||
|
||||
// MANAGE USER (own account)
|
||||
const [usernameUser, setUsernameUser] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (currentUser?.username) {
|
||||
setUsernameUser(currentUser.username);
|
||||
}
|
||||
}, [currentUser]);
|
||||
|
||||
//update user mutation
|
||||
const updateUserMutate = useMutation({
|
||||
mutationFn: async (
|
||||
updates: Partial<{ username: string; password: string }>,
|
||||
) => {
|
||||
mutationFn: async (updates: Partial<{ username: string; password: string }>) => {
|
||||
if (!currentUser?.id) throw new Error("User not loaded");
|
||||
const res = await apiRequest("PUT", `/api/users/${currentUser.id}`, updates);
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json().catch(() => null);
|
||||
throw new Error(errorData?.error || "Failed to update user");
|
||||
}
|
||||
if (!res.ok) { const e = await res.json().catch(() => null); throw new Error(e?.error || "Failed to update user"); }
|
||||
return res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["/api/users/"] });
|
||||
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",
|
||||
});
|
||||
},
|
||||
onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["/api/users/"] }); toast({ title: "Updated", description: "Your profile has been updated." }); },
|
||||
onError: (e: any) => toast({ title: "Error", description: e?.message, variant: "destructive" }),
|
||||
});
|
||||
|
||||
// ── Section renderer ───────────────────────────────────────────
|
||||
const renderSection = () => {
|
||||
switch (section) {
|
||||
case "staff":
|
||||
return (
|
||||
<div>
|
||||
<Card>
|
||||
<CardContent>
|
||||
<div className="mt-8">
|
||||
<div className="mt-4">
|
||||
<StaffTable
|
||||
staff={staff}
|
||||
isLoading={isLoading}
|
||||
isError={isError}
|
||||
onAdd={openAddStaffModal}
|
||||
onEdit={openEditStaffModal}
|
||||
onDelete={handleDeleteStaff}
|
||||
onView={handleViewStaff}
|
||||
isLoading={staffLoading}
|
||||
isError={staffError}
|
||||
onAdd={() => { setEditingStaff(null); setModalOpen(true); }}
|
||||
onEdit={(s) => { setEditingStaff(s); setModalOpen(true); }}
|
||||
onDelete={(s) => { setCurrentStaff(s); setIsDeleteStaffOpen(true); }}
|
||||
onView={(s) => alert(`Viewing staff member:\n${s.name} (${s.email || "No email"})`)}
|
||||
/>
|
||||
{isError && (
|
||||
<p className="mt-4 text-red-600">
|
||||
{(error as Error)?.message || "Failed to load staff data."}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{staffError && <p className="mt-4 text-red-600">{(staffErrorMsg as Error)?.message || "Failed to load staff data."}</p>}
|
||||
<DeleteConfirmationDialog
|
||||
isOpen={isDeleteStaffOpen}
|
||||
onConfirm={handleConfirmDeleteStaff}
|
||||
onConfirm={() => { if (currentStaff?.id) deleteStaffMutation.mutate(currentStaff.id); }}
|
||||
onCancel={() => setIsDeleteStaffOpen(false)}
|
||||
entityName={currentStaff?.name}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
{/* Modal Overlay */}
|
||||
{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={handleFormSubmit}
|
||||
onCancel={handleModalCancel}
|
||||
isLoading={isAdding || isUpdating}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Manage Users section (admin only) */}
|
||||
{isAdmin && (
|
||||
<Card className="mt-6">
|
||||
case "users":
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="space-y-4 py-6">
|
||||
<h3 className="text-lg font-semibold">Manage Users</h3>
|
||||
|
||||
{/* Existing users list */}
|
||||
<div className="border rounded divide-y">
|
||||
{allUsers.length === 0 && (
|
||||
<p className="text-sm text-gray-500 p-3">No users found.</p>
|
||||
)}
|
||||
{allUsers.length === 0 && <p className="text-sm text-gray-500 p-3">No users found.</p>}
|
||||
{allUsers.map((u) => (
|
||||
<div key={u.id} className="flex items-center justify-between px-3 py-2">
|
||||
<span className="text-sm font-medium">{u.username}</span>
|
||||
{u.username !== "admin" && (
|
||||
<button
|
||||
className="text-sm text-red-600 hover:underline"
|
||||
onClick={() => deleteUserMutation.mutate(u.id)}
|
||||
disabled={deleteUserMutation.isPending}
|
||||
>
|
||||
<button className="text-sm text-red-600 hover:underline" onClick={() => deleteUserMutation.mutate(u.id)} disabled={deleteUserMutation.isPending}>
|
||||
Delete
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Add new user form */}
|
||||
<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>
|
||||
<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 User</h4>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Username</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newUsername}
|
||||
onChange={(e) => setNewUsername(e.target.value)}
|
||||
className="mt-1 p-2 border rounded w-full"
|
||||
placeholder="Enter username"
|
||||
required
|
||||
/>
|
||||
<input 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>
|
||||
<label className="block text-sm font-medium">Password</label>
|
||||
<div className="relative mt-1">
|
||||
<input
|
||||
type={showNewUserPassword ? "text" : "password"}
|
||||
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}
|
||||
>
|
||||
<input type={showNewUserPassword ? "text" : "password"} 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} />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
className="bg-teal-600 text-white px-4 py-2 rounded hover:bg-teal-700"
|
||||
disabled={addUserMutation.isPending}
|
||||
>
|
||||
{addUserMutation.isPending ? "Adding..." : "Add"}
|
||||
<button type="submit" className="bg-teal-600 text-white px-4 py-2 rounded hover:bg-teal-700" disabled={addUserMutation.isPending}>
|
||||
{addUserMutation.isPending ? "Adding..." : "Add User"}
|
||||
</button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
);
|
||||
|
||||
{/* User Setting section */}
|
||||
<Card className="mt-6">
|
||||
case "account":
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="space-y-4 py-6">
|
||||
<h3 className="text-lg font-semibold">Admin Settings</h3>
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
<h3 className="text-lg font-semibold">Account Settings</h3>
|
||||
<form className="space-y-4" onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(e.currentTarget);
|
||||
const password =
|
||||
formData.get("password")?.toString().trim() || undefined;
|
||||
|
||||
updateUserMutate.mutate({
|
||||
...(isAdmin ? {} : { username: usernameUser?.trim() || undefined }),
|
||||
password: password || undefined,
|
||||
});
|
||||
}}
|
||||
>
|
||||
const password = formData.get("password")?.toString().trim() || undefined;
|
||||
updateUserMutate.mutate({ ...(isAdmin ? {} : { username: usernameUser?.trim() || undefined }), password: password || undefined });
|
||||
}}>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Username</label>
|
||||
<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}
|
||||
/>
|
||||
{isAdmin && (
|
||||
<p className="text-xs text-gray-500 mt-1">Admin username cannot be changed.</p>
|
||||
)}
|
||||
<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} />
|
||||
{isAdmin && <p className="text-xs text-gray-500 mt-1">Admin username cannot be changed.</p>}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium">New Password</label>
|
||||
<div className="relative mt-1">
|
||||
<input
|
||||
type={showAdminPassword ? "text" : "password"}
|
||||
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}
|
||||
>
|
||||
<input type={showAdminPassword ? "text" : "password"} 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} />}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Leave blank to keep current password.
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-1">Leave blank to keep current password.</p>
|
||||
</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"}
|
||||
</button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
{/* Twilio Section */}
|
||||
<div className="mt-6">
|
||||
<TwilioSettingsCard />
|
||||
</div>
|
||||
case "credentials":
|
||||
return <CredentialTable />;
|
||||
|
||||
{/* Credential Section */}
|
||||
<div className="mt-6">
|
||||
<CredentialTable />
|
||||
</div>
|
||||
case "npi":
|
||||
return <NpiProviderTable />;
|
||||
|
||||
{/* NpiProvider Section */}
|
||||
<div className="mt-6">
|
||||
<NpiProviderTable />
|
||||
</div>
|
||||
case "programs":
|
||||
return <ProgramBridgeTable />;
|
||||
|
||||
{/* Program Bridge Section */}
|
||||
<div className="mt-6">
|
||||
<ProgramBridgeTable />
|
||||
case "twilio":
|
||||
return <TwilioSettingsCard />;
|
||||
|
||||
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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user