feat: improve backup management, settings UI, and Twilio webhooks
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -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();
|
||||
}
|
||||
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,28 +276,36 @@ 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 (
|
||||
<Link
|
||||
to={child.path}
|
||||
key={child.path}
|
||||
onClick={() => setOpenMobile(false)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center space-x-2 p-2 rounded-md pl-2 mb-0.5 transition-colors cursor-pointer",
|
||||
isActive
|
||||
? "text-primary font-medium bg-primary/5 border-l-2 border-primary"
|
||||
: "text-gray-500 hover:bg-gray-100 hover:text-gray-700"
|
||||
)}
|
||||
<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}
|
||||
onClick={() => setOpenMobile(false)}
|
||||
>
|
||||
{child.icon}
|
||||
<span className="whitespace-nowrap select-none text-sm">
|
||||
{child.name}
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center space-x-2 p-2 rounded-md pl-2 mb-0.5 transition-colors cursor-pointer",
|
||||
isActive
|
||||
? "text-primary font-medium bg-primary/5 border-l-2 border-primary"
|
||||
: "text-gray-500 hover:bg-gray-100 hover:text-gray-700"
|
||||
)}
|
||||
>
|
||||
{child.icon}
|
||||
<span className="whitespace-nowrap select-none text-sm">
|
||||
{child.name}
|
||||
</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 (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<div className="mt-4">
|
||||
<StaffTable
|
||||
staff={staff}
|
||||
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"})`)}
|
||||
/>
|
||||
{staffError && <p className="mt-4 text-red-600">{(staffErrorMsg as Error)?.message || "Failed to load staff data."}</p>}
|
||||
<DeleteConfirmationDialog
|
||||
isOpen={isDeleteStaffOpen}
|
||||
onConfirm={() => { if (currentStaff?.id) deleteStaffMutation.mutate(currentStaff.id); }}
|
||||
onCancel={() => setIsDeleteStaffOpen(false)}
|
||||
entityName={currentStaff?.name}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
case "users":
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="space-y-4 py-6">
|
||||
<h3 className="text-lg font-semibold">Manage Users</h3>
|
||||
<div className="border rounded divide-y">
|
||||
{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}>
|
||||
Delete
|
||||
</button>
|
||||
)}
|
||||
</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() }); }}>
|
||||
<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 />
|
||||
</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}>
|
||||
{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 User"}
|
||||
</button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
case "account":
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="space-y-4 py-6">
|
||||
<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 });
|
||||
}}>
|
||||
<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>}
|
||||
</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}>
|
||||
{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>
|
||||
</div>
|
||||
<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>
|
||||
);
|
||||
|
||||
case "credentials":
|
||||
return <CredentialTable />;
|
||||
|
||||
case "npi":
|
||||
return <NpiProviderTable />;
|
||||
|
||||
case "programs":
|
||||
return <ProgramBridgeTable />;
|
||||
|
||||
case "twilio":
|
||||
return <TwilioSettingsCard />;
|
||||
|
||||
case "ai":
|
||||
return <AiSettingsCard />;
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Card>
|
||||
<CardContent>
|
||||
<div className="mt-8">
|
||||
<StaffTable
|
||||
staff={staff}
|
||||
isLoading={isLoading}
|
||||
isError={isError}
|
||||
onAdd={openAddStaffModal}
|
||||
onEdit={openEditStaffModal}
|
||||
onDelete={handleDeleteStaff}
|
||||
onView={handleViewStaff}
|
||||
/>
|
||||
{isError && (
|
||||
<p className="mt-4 text-red-600">
|
||||
{(error as Error)?.message || "Failed to load staff data."}
|
||||
</p>
|
||||
)}
|
||||
<>
|
||||
{renderSection()}
|
||||
|
||||
<DeleteConfirmationDialog
|
||||
isOpen={isDeleteStaffOpen}
|
||||
onConfirm={handleConfirmDeleteStaff}
|
||||
onCancel={() => setIsDeleteStaffOpen(false)}
|
||||
entityName={currentStaff?.name}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Modal Overlay */}
|
||||
{/* 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>
|
||||
<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}
|
||||
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>
|
||||
)}
|
||||
|
||||
{/* Manage Users section (admin only) */}
|
||||
{isAdmin && (
|
||||
<Card className="mt-6">
|
||||
<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.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}
|
||||
>
|
||||
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>
|
||||
<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
|
||||
/>
|
||||
</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}
|
||||
>
|
||||
{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>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* User Setting section */}
|
||||
<Card className="mt-6">
|
||||
<CardContent className="space-y-4 py-6">
|
||||
<h3 className="text-lg font-semibold">Admin 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,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<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>
|
||||
)}
|
||||
</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}
|
||||
>
|
||||
{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>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
|
||||
{/* Credential Section */}
|
||||
<div className="mt-6">
|
||||
<CredentialTable />
|
||||
</div>
|
||||
|
||||
{/* NpiProvider Section */}
|
||||
<div className="mt-6">
|
||||
<NpiProviderTable />
|
||||
</div>
|
||||
|
||||
{/* Program Bridge Section */}
|
||||
<div className="mt-6">
|
||||
<ProgramBridgeTable />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user