feat(eligibility-check) - add CCA eligibility workflow with new routes and frontend components; enhance patient data processing and eligibility status updates; update insurance provider handling across various workflows

This commit is contained in:
2026-02-25 22:38:33 -05:00
parent 27e6e6a4a0
commit 4cb7ec7e2e
26 changed files with 2893 additions and 346 deletions

View File

@@ -41,7 +41,7 @@ function Router() {
component={() => <AppointmentsPage />}
/>
<ProtectedRoute path="/patients" component={() => <PatientsPage />} />
<ProtectedRoute path="/settings" component={() => <SettingsPage />} />
<ProtectedRoute path="/settings" component={() => <SettingsPage />} adminOnly />
<ProtectedRoute path="/claims" component={() => <ClaimsPage />} />
<ProtectedRoute
path="/insurance-status"

View File

@@ -0,0 +1,357 @@
import { useEffect, useRef, useState } from "react";
import { io as ioClient, Socket } from "socket.io-client";
import { Button } from "@/components/ui/button";
import { CheckCircle, LoaderCircleIcon } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useAppDispatch } from "@/redux/hooks";
import { setTaskStatus } from "@/redux/slices/seleniumEligibilityCheckTaskSlice";
import { formatLocalDate } from "@/utils/dateUtils";
import { QK_PATIENTS_BASE } from "@/components/patients/patient-table";
const SOCKET_URL =
import.meta.env.VITE_API_BASE_URL_BACKEND ||
(typeof window !== "undefined" ? window.location.origin : "");
interface CCAEligibilityButtonProps {
memberId: string;
dateOfBirth: Date | null;
firstName?: string;
lastName?: string;
isFormIncomplete: boolean;
onPdfReady: (pdfId: number, fallbackFilename: string | null) => void;
}
export function CCAEligibilityButton({
memberId,
dateOfBirth,
firstName,
lastName,
isFormIncomplete,
onPdfReady,
}: CCAEligibilityButtonProps) {
const { toast } = useToast();
const dispatch = useAppDispatch();
const isCCAFormIncomplete =
!dateOfBirth || (!memberId && !firstName && !lastName);
const socketRef = useRef<Socket | null>(null);
const connectingRef = useRef<Promise<void> | null>(null);
const [isStarting, setIsStarting] = useState(false);
useEffect(() => {
return () => {
if (socketRef.current) {
socketRef.current.removeAllListeners();
socketRef.current.disconnect();
socketRef.current = null;
}
connectingRef.current = null;
};
}, []);
const closeSocket = () => {
try {
socketRef.current?.removeAllListeners();
socketRef.current?.disconnect();
} catch (e) {
// ignore
} finally {
socketRef.current = null;
}
};
const ensureSocketConnected = async () => {
if (socketRef.current && socketRef.current.connected) {
return;
}
if (connectingRef.current) {
return connectingRef.current;
}
const promise = new Promise<void>((resolve, reject) => {
const socket = ioClient(SOCKET_URL, {
withCredentials: true,
});
socketRef.current = socket;
socket.on("connect", () => {
resolve();
});
socket.on("connect_error", () => {
dispatch(
setTaskStatus({
status: "error",
message: "Connection failed",
})
);
toast({
title: "Realtime connection failed",
description:
"Could not connect to realtime server. Retrying automatically...",
variant: "destructive",
});
});
socket.on("reconnect_failed", () => {
dispatch(
setTaskStatus({
status: "error",
message: "Reconnect failed",
})
);
closeSocket();
reject(new Error("Realtime reconnect failed"));
});
socket.on("disconnect", () => {
dispatch(
setTaskStatus({
status: "error",
message: "Connection disconnected",
})
);
});
socket.on("selenium:session_update", (payload: any) => {
const { session_id, status, final } = payload || {};
if (!session_id) return;
if (status === "completed") {
dispatch(
setTaskStatus({
status: "success",
message:
"CCA eligibility updated and PDF attached to patient documents.",
})
);
toast({
title: "CCA eligibility complete",
description:
"Patient status was updated and the eligibility PDF was saved.",
variant: "default",
});
const pdfId = final?.pdfFileId;
if (pdfId) {
const filename =
final?.pdfFilename ?? `eligibility_cca_${memberId}.pdf`;
onPdfReady(Number(pdfId), filename);
}
} else if (status === "error") {
const msg =
payload?.message ||
final?.error ||
"CCA eligibility session failed.";
dispatch(
setTaskStatus({
status: "error",
message: msg,
})
);
toast({
title: "CCA selenium error",
description: msg,
variant: "destructive",
});
try {
closeSocket();
} catch (e) {}
}
queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
});
socket.on("selenium:session_error", (payload: any) => {
const msg = payload?.message || "Selenium session error";
dispatch(
setTaskStatus({
status: "error",
message: msg,
})
);
toast({
title: "Selenium session error",
description: msg,
variant: "destructive",
});
try {
closeSocket();
} catch (e) {}
});
const initialConnectTimeout = setTimeout(() => {
if (!socket.connected) {
closeSocket();
reject(new Error("Realtime initial connection timeout"));
}
}, 8000);
socket.once("connect", () => {
clearTimeout(initialConnectTimeout);
});
});
connectingRef.current = promise;
try {
await promise;
} finally {
connectingRef.current = null;
}
};
const startCCAEligibility = async () => {
if (!dateOfBirth) {
toast({
title: "Missing fields",
description: "Date of Birth is required for CCA eligibility.",
variant: "destructive",
});
return;
}
if (!memberId && !firstName && !lastName) {
toast({
title: "Missing fields",
description:
"Member ID, First Name, or Last Name is required for CCA eligibility.",
variant: "destructive",
});
return;
}
const formattedDob = dateOfBirth ? formatLocalDate(dateOfBirth) : "";
const payload = {
memberId: memberId || "",
dateOfBirth: formattedDob,
firstName: firstName || "",
lastName: lastName || "",
insuranceSiteKey: "CCA",
};
try {
setIsStarting(true);
dispatch(
setTaskStatus({
status: "pending",
message: "Opening realtime channel for CCA eligibility...",
})
);
await ensureSocketConnected();
const socket = socketRef.current;
if (!socket || !socket.connected) {
throw new Error("Socket connection failed");
}
const socketId = socket.id;
dispatch(
setTaskStatus({
status: "pending",
message: "Starting CCA eligibility check via selenium...",
})
);
const response = await apiRequest(
"POST",
"/api/insurance-status-cca/cca-eligibility",
{
data: JSON.stringify(payload),
socketId,
}
);
let result: any = null;
let backendError: string | null = null;
try {
result = await response.clone().json();
backendError =
result?.error || result?.message || result?.detail || null;
} catch {
try {
const text = await response.clone().text();
backendError = text?.trim() || null;
} catch {
backendError = null;
}
}
if (!response.ok) {
throw new Error(
backendError ||
`CCA selenium start failed (status ${response.status})`
);
}
if (result?.error) {
throw new Error(result.error);
}
if (result.status === "started" && result.session_id) {
dispatch(
setTaskStatus({
status: "pending",
message:
"CCA eligibility job started. Waiting for result...",
})
);
} else {
dispatch(
setTaskStatus({
status: "success",
message: "CCA eligibility completed.",
})
);
}
} catch (err: any) {
console.error("startCCAEligibility error:", err);
dispatch(
setTaskStatus({
status: "error",
message: err?.message || "Failed to start CCA eligibility",
})
);
toast({
title: "CCA selenium error",
description: err?.message || "Failed to start CCA eligibility",
variant: "destructive",
});
} finally {
setIsStarting(false);
}
};
return (
<Button
className="w-full"
disabled={isCCAFormIncomplete || isStarting}
onClick={startCCAEligibility}
>
{isStarting ? (
<>
<LoaderCircleIcon className="h-4 w-4 mr-2 animate-spin" />
Processing...
</>
) : (
<>
<CheckCircle className="h-4 w-4 mr-2" />
CCA
</>
)}
</Button>
);
}

View File

@@ -16,10 +16,16 @@ import {
import { cn } from "@/lib/utils";
import { useMemo } from "react";
import { useSidebar } from "@/components/ui/sidebar";
import { useAuth } from "@/hooks/use-auth";
export function Sidebar() {
const [location] = useLocation();
const { state, openMobile, setOpenMobile } = useSidebar(); // "expanded" | "collapsed"
const { state, openMobile, setOpenMobile } = useSidebar();
const { user } = useAuth();
const isAdmin =
user?.role?.toUpperCase() === "ADMIN" ||
user?.username?.toLowerCase() === "admin";
const navItems = useMemo(
() => [
@@ -82,6 +88,7 @@ export function Sidebar() {
name: "Settings",
path: "/settings",
icon: <Settings className="h-5 w-5" />,
adminOnly: true,
},
],
[]
@@ -90,43 +97,39 @@ export function Sidebar() {
return (
<div
className={cn(
// original look
"bg-white border-r border-gray-200 shadow-sm z-20",
// clip during width animation to avoid text peeking
"overflow-hidden will-change-[width]",
// animate width only
"transition-[width] duration-200 ease-in-out",
// MOBILE: overlay below topbar (h = 100vh - 4rem)
openMobile
? "fixed top-16 left-0 h-[calc(100vh-4rem)] w-64 block md:hidden"
: "hidden md:block",
// DESKTOP: participates in row layout
"md:static md:top-auto md:h-auto md:flex-shrink-0",
state === "collapsed" ? "md:w-0 overflow-hidden" : "md:w-64"
)}
>
<div className="p-2">
<nav role="navigation" aria-label="Main">
{navItems.map((item) => (
<div key={item.path}>
<Link to={item.path} onClick={() => setOpenMobile(false)}>
<div
className={cn(
"flex items-center space-x-3 p-2 rounded-md pl-3 mb-1 transition-colors cursor-pointer",
location === item.path
? "text-primary font-medium border-l-2 border-primary"
: "text-gray-600 hover:bg-gray-100"
)}
>
{item.icon}
{/* show label only after expand animation completes */}
<span className="whitespace-nowrap select-none">
{item.name}
</span>
</div>
</Link>
</div>
))}
{navItems
.filter((item) => !item.adminOnly || isAdmin)
.map((item) => (
<div key={item.path}>
<Link to={item.path} onClick={() => setOpenMobile(false)}>
<div
className={cn(
"flex items-center space-x-3 p-2 rounded-md pl-3 mb-1 transition-colors cursor-pointer",
location === item.path
? "text-primary font-medium border-l-2 border-primary"
: "text-gray-600 hover:bg-gray-100"
)}
>
{item.icon}
<span className="whitespace-nowrap select-none">
{item.name}
</span>
</div>
</Link>
</div>
))}
</nav>
</div>
</div>

View File

@@ -21,6 +21,7 @@ const SITE_KEY_OPTIONS = [
{ value: "DELTAINS", label: "Delta Dental Ins" },
{ value: "DENTAQUEST", label: "Tufts SCO / DentaQuest" },
{ value: "UNITEDSCO", label: "United SCO" },
{ value: "CCA", label: "CCA" },
];
export function CredentialForm({ onClose, userId, defaultValues }: CredentialFormProps) {

View File

@@ -20,6 +20,7 @@ const SITE_KEY_LABELS: Record<string, string> = {
DELTAINS: "Delta Dental Ins",
DENTAQUEST: "Tufts SCO / DentaQuest",
UNITEDSCO: "United SCO",
CCA: "CCA",
};
function getSiteKeyLabel(siteKey: string): string {

View File

@@ -4,28 +4,32 @@ import { useAuth } from "@/hooks/use-auth";
import { Suspense } from "react";
import { Redirect, Route } from "wouter";
type ComponentLike = React.ComponentType; // works for both lazy() and regular components
type ComponentLike = React.ComponentType;
export function ProtectedRoute({
path,
component: Component,
adminOnly,
}: {
path: string;
component: ComponentLike;
adminOnly?: boolean;
}) {
const { user, isLoading } = useAuth();
return (
<Route path={path}>
{/* While auth is resolving: keep layout visible and show a small spinner in the content area */}
{isLoading ? (
<AppLayout>
<LoadingScreen />
</AppLayout>
) : !user ? (
<Redirect to="/auth" />
) : adminOnly &&
user.role?.toUpperCase() !== "ADMIN" &&
user.username?.toLowerCase() !== "admin" ? (
<Redirect to="/dashboard" />
) : (
// Authenticated: render page inside layout. Lazy pages load with an in-layout spinner.
<AppLayout>
<Suspense fallback={<LoadingScreen />}>
<Component />

View File

@@ -1,6 +1,6 @@
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useState } from "react";
import { useEffect } from "react";
import { useAuth } from "@/hooks/use-auth";
import { Button } from "@/components/ui/button";
import {
@@ -12,7 +12,6 @@ import {
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Checkbox } from "@/components/ui/checkbox";
import { Card } from "@/components/ui/card";
import { CheckCircle, Torus } from "lucide-react";
@@ -22,13 +21,10 @@ import { useLocation } from "wouter";
import {
LoginFormValues,
loginSchema,
RegisterFormValues,
registerSchema,
} from "@repo/db/types";
export default function AuthPage() {
const [activeTab, setActiveTab] = useState<string>("login");
const { isLoading, user, loginMutation, registerMutation } = useAuth();
const { isLoading, user, loginMutation } = useAuth();
const [, navigate] = useLocation();
const loginForm = useForm<LoginFormValues>({
@@ -40,37 +36,20 @@ export default function AuthPage() {
},
});
const registerForm = useForm<RegisterFormValues>({
resolver: zodResolver(registerSchema),
defaultValues: {
username: "",
password: "",
confirmPassword: "",
agreeTerms: false,
},
});
const onLoginSubmit = (data: LoginFormValues) => {
loginMutation.mutate({ username: data.username, password: data.password });
};
const onRegisterSubmit = (data: RegisterFormValues) => {
registerMutation.mutate({
username: data.username,
password: data.password,
});
};
if (isLoading) {
return <LoadingScreen />;
}
useEffect(() => {
if (user) {
navigate("/insurance-status");
}
}, [user, navigate]);
if (isLoading) {
return <LoadingScreen />;
}
return (
<div className="min-h-screen bg-gray-100 flex items-center justify-center">
<div className="w-full max-w-4xl grid grid-cols-1 md:grid-cols-2 shadow-lg rounded-lg overflow-hidden">
@@ -81,198 +60,78 @@ export default function AuthPage() {
My Dental Office Management
</h1>
<p className="text-gray-600">
{" "}
Comprehensive Practice Management System
</p>
</div>
<Tabs
defaultValue="login"
value={activeTab}
onValueChange={setActiveTab}
>
<TabsList className="grid w-full grid-cols-2 mb-6">
<TabsTrigger value="login">Login</TabsTrigger>
<TabsTrigger value="register">Register</TabsTrigger>
</TabsList>
<Form {...loginForm}>
<form
onSubmit={loginForm.handleSubmit(onLoginSubmit)}
className="space-y-4"
>
<FormField
control={loginForm.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormControl>
<Input placeholder="Enter your username" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<TabsContent value="login">
<Form {...loginForm}>
<form
onSubmit={loginForm.handleSubmit(onLoginSubmit)}
className="space-y-4"
>
<FormField
control={loginForm.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormControl>
<Input placeholder="Enter your username" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={loginForm.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input
placeholder="••••••••"
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={loginForm.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input
placeholder="••••••••"
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex items-center justify-between">
<FormField
control={loginForm.control}
name="rememberMe"
render={({ field }) => (
<div className="flex items-center space-x-2">
<Checkbox
id="remember-me"
checked={field.value as CheckedState}
onCheckedChange={field.onChange}
/>
<label
htmlFor="remember-me"
className="text-sm font-medium text-gray-700"
>
Remember me
</label>
</div>
)}
/>
</div>
<div className="flex items-center justify-between">
<FormField
control={loginForm.control}
name="rememberMe"
render={({ field }) => (
<div className="flex items-center space-x-2">
<Checkbox
id="remember-me"
checked={field.value as CheckedState}
onCheckedChange={field.onChange}
/>
<label
htmlFor="remember-me"
className="text-sm font-medium text-gray-700"
>
Remember me
</label>
</div>
)}
/>
<button
type="button"
onClick={() => {
// do something if needed
}}
className="text-sm font-medium text-primary hover:text-primary/80"
>
Forgot password?
</button>
</div>
<Button
type="submit"
className="w-full"
disabled={loginMutation.isPending}
>
{loginMutation.isPending ? "Signing in..." : "Sign in"}
</Button>
</form>
</Form>
</TabsContent>
<TabsContent value="register">
<Form {...registerForm}>
<form
onSubmit={registerForm.handleSubmit(onRegisterSubmit)}
className="space-y-4"
>
<FormField
control={registerForm.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormControl>
<Input placeholder="Choose a username" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={registerForm.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input
placeholder="••••••••"
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={registerForm.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormLabel>Confirm Password</FormLabel>
<FormControl>
<Input
placeholder="••••••••"
type="password"
{...field}
value={
typeof field.value === "string" ? field.value : ""
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={registerForm.control}
name="agreeTerms"
render={({ field }) => (
<FormItem className="flex space-x-2 items-center">
<FormControl>
<Checkbox
checked={field.value as CheckedState}
onCheckedChange={field.onChange}
className="mt-2.5"
/>
</FormControl>
<div className="">
<FormLabel className="text-sm font-bold leading-tight">
I agree to the{" "}
<a href="#" className="text-primary underline">
Terms and Conditions
</a>
</FormLabel>
<FormMessage />
</div>
</FormItem>
)}
/>
<Button
type="submit"
className="w-full"
disabled={registerMutation.isPending}
>
{registerMutation.isPending
? "Creating Account..."
: "Create Account"}
</Button>
</form>
</Form>
</TabsContent>
</Tabs>
<Button
type="submit"
className="w-full"
disabled={loginMutation.isPending}
>
{loginMutation.isPending ? "Signing in..." : "Sign in"}
</Button>
</form>
</Form>
</Card>
{/* Hero Section */}

View File

@@ -31,6 +31,7 @@ import { DdmaEligibilityButton } from "@/components/insurance-status/ddma-buton-
import { DentaQuestEligibilityButton } from "@/components/insurance-status/dentaquest-button-modal";
import { UnitedSCOEligibilityButton } from "@/components/insurance-status/unitedsco-button-modal";
import { DeltaInsEligibilityButton } from "@/components/insurance-status/deltains-button-modal";
import { CCAEligibilityButton } from "@/components/insurance-status/cca-button-modal";
export default function InsuranceStatusPage() {
const { user } = useAuth();
@@ -655,14 +656,20 @@ export default function InsuranceStatusPage() {
}}
/>
<Button
className="w-full"
variant="outline"
disabled={isFormIncomplete}
>
<CheckCircle className="h-4 w-4 mr-2" />
CCA
</Button>
<CCAEligibilityButton
memberId={memberId}
dateOfBirth={dateOfBirth}
firstName={firstName}
lastName={lastName}
isFormIncomplete={isFormIncomplete}
onPdfReady={(pdfId, fallbackFilename) => {
setPreviewPdfId(pdfId);
setPreviewFallbackFilename(
fallbackFilename ?? `eligibility_cca_${memberId}.pdf`
);
setPreviewOpen(true);
}}
/>
</div>
{/* Row 3 */}

View File

@@ -10,19 +10,18 @@ import { CredentialTable } from "@/components/settings/insuranceCredTable";
import { useAuth } from "@/hooks/use-auth";
import { Staff } from "@repo/db/types";
type SafeUser = { id: number; username: string; role: "ADMIN" | "USER" };
export default function SettingsPage() {
const { toast } = useToast();
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
// Modal and editing 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,
@@ -37,14 +36,13 @@ export default function SettingsPage() {
}
return res.json();
},
staleTime: 1000 * 60 * 5, // 5 minutes cache
staleTime: 1000 * 60 * 5,
});
// Add Staff mutation
const addStaffMutate = useMutation<
Staff, // Return type
Error, // Error type
Omit<Staff, "id" | "createdAt"> // Variables
Staff,
Error,
Omit<Staff, "id" | "createdAt">
>({
mutationFn: async (newStaff: Omit<Staff, "id" | "createdAt">) => {
const res = await apiRequest("POST", "/api/staffs/", newStaff);
@@ -71,7 +69,6 @@ export default function SettingsPage() {
},
});
// Update Staff mutation
const updateStaffMutate = useMutation<
Staff,
Error,
@@ -108,7 +105,6 @@ export default function SettingsPage() {
},
});
// Delete Staff mutation
const deleteStaffMutation = useMutation<number, Error, number>({
mutationFn: async (id: number) => {
const res = await apiRequest("DELETE", `/api/staffs/${id}`);
@@ -136,30 +132,24 @@ export default function SettingsPage() {
},
});
// 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" | "createdAt">) => {
if (editingStaff) {
// Editing existing staff
if (editingStaff.id === undefined) {
toast({
title: "Error",
@@ -181,7 +171,6 @@ export default function SettingsPage() {
setModalOpen(false);
};
// Close modal on successful add/update
useEffect(() => {
if (isAddSuccess || isUpdateSuccess) {
setModalOpen(false);
@@ -215,10 +204,86 @@ export default function SettingsPage() {
`Viewing staff member:\n${staff.name} (${staff.email || "No email"})`
);
// MANAGE USER
// --- Users control (list, add, edit password, delete) ---
const {
data: usersList = [],
isLoading: usersLoading,
isError: usersError,
error: usersErrorObj,
} = useQuery<SafeUser[]>({
queryKey: ["/api/users/list"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/users/list");
if (!res.ok) throw new Error("Failed to fetch users");
return res.json();
},
staleTime: 1000 * 60 * 2,
});
const addUserMutate = useMutation<SafeUser, Error, { username: string; password: string; role?: "ADMIN" | "USER" }>({
mutationFn: async (data) => {
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 add user");
}
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/users/list"] });
setAddUserModalOpen(false);
toast({ title: "User Added", description: "User created successfully.", variant: "default" });
},
onError: (e: any) => {
toast({ title: "Error", description: e?.message || "Failed to add user", variant: "destructive" });
},
});
const updateUserPasswordMutate = useMutation<SafeUser, Error, { id: number; password: string }>({
mutationFn: async ({ id, password }) => {
const res = await apiRequest("PUT", `/api/users/${id}`, { password });
if (!res.ok) {
const err = await res.json().catch(() => null);
throw new Error(err?.error || "Failed to update password");
}
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/users/list"] });
setEditPasswordUser(null);
toast({ title: "Password Updated", description: "Password changed successfully.", variant: "default" });
},
onError: (e: any) => {
toast({ title: "Error", description: e?.message || "Failed to update password", variant: "destructive" });
},
});
const deleteUserMutate = useMutation<number, Error, number>({
mutationFn: async (id) => {
const res = await apiRequest("DELETE", `/api/users/${id}`);
if (!res.ok) {
const err = await res.json().catch(() => null);
throw new Error(err?.error || "Failed to delete user");
}
return id;
},
onSuccess: () => {
setUserToDelete(null);
queryClient.invalidateQueries({ queryKey: ["/api/users/list"] });
toast({ title: "User Removed", description: "User deleted.", variant: "default" });
},
onError: (e: any) => {
toast({ title: "Error", description: e?.message || "Failed to delete user", variant: "destructive" });
},
});
const [addUserModalOpen, setAddUserModalOpen] = useState(false);
const [editPasswordUser, setEditPasswordUser] = useState<SafeUser | null>(null);
const [userToDelete, setUserToDelete] = useState<SafeUser | null>(null);
// MANAGE USER (current user profile)
const [usernameUser, setUsernameUser] = useState("");
//fetch user
const { user } = useAuth();
useEffect(() => {
if (user?.username) {
@@ -226,7 +291,6 @@ export default function SettingsPage() {
}
}, [user]);
//update user mutation
const updateUserMutate = useMutation({
mutationFn: async (
updates: Partial<{ username: string; password: string }>
@@ -303,10 +367,73 @@ export default function SettingsPage() {
</div>
)}
{/* User Setting section */}
{/* Users control section */}
<Card className="mt-6">
<CardContent className="py-6">
<div className="flex justify-between items-center mb-4">
<h3 className="text-lg font-semibold">User Accounts</h3>
<button
type="button"
onClick={() => setAddUserModalOpen(true)}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
>
Add User
</button>
</div>
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Username</th>
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Role</th>
<th className="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Actions</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{usersLoading && (
<tr><td colSpan={3} className="px-4 py-4 text-gray-500">Loading users...</td></tr>
)}
{usersError && (
<tr><td colSpan={3} className="px-4 py-4 text-red-600">{(usersErrorObj as Error)?.message}</td></tr>
)}
{!usersLoading && !usersError && usersList.filter((u) => u.id !== user?.id).length === 0 && (
<tr><td colSpan={3} className="px-4 py-4 text-gray-500">No other users.</td></tr>
)}
{!usersLoading && usersList.filter((u) => u.id !== user?.id).map((u) => (
<tr key={u.id}>
<td className="px-4 py-2">
<span>{u.username}</span>
</td>
<td className="px-4 py-2">{u.role}</td>
<td className="px-4 py-2 text-right space-x-2">
<button
type="button"
onClick={() => setEditPasswordUser(u)}
className="text-blue-600 hover:underline"
>
Edit password
</button>
<button
type="button"
onClick={() => setUserToDelete(u)}
className="text-red-600 hover:underline"
title="Delete user"
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</CardContent>
</Card>
{/* User Setting section (current user profile) */}
<Card className="mt-6">
<CardContent className="space-y-4 py-6">
<h3 className="text-lg font-semibold">User Settings</h3>
<h3 className="text-lg font-semibold">Admin Setting</h3>
<form
className="space-y-4"
onSubmit={(e) => {
@@ -358,6 +485,96 @@ export default function SettingsPage() {
</CardContent>
</Card>
{/* Add User modal */}
{addUserModalOpen && (
<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">Add User</h2>
<form
onSubmit={(e) => {
e.preventDefault();
const form = e.currentTarget;
const username = (form.querySelector('[name="new-username"]') as HTMLInputElement)?.value?.trim();
const password = (form.querySelector('[name="new-password"]') as HTMLInputElement)?.value;
const role = (form.querySelector('[name="new-role"]') as HTMLSelectElement)?.value as "ADMIN" | "USER";
if (!username || !password) {
toast({ title: "Error", description: "Username and password are required.", variant: "destructive" });
return;
}
addUserMutate.mutate({ username, password, role: role || "USER" });
}}
className="space-y-4"
>
<div>
<label className="block text-sm font-medium">Username</label>
<input name="new-username" type="text" required className="mt-1 p-2 border rounded w-full" />
</div>
<div>
<label className="block text-sm font-medium">Password</label>
<input name="new-password" type="password" required className="mt-1 p-2 border rounded w-full" placeholder="••••••••" />
</div>
<div>
<label className="block text-sm font-medium">Role</label>
<select name="new-role" className="mt-1 p-2 border rounded w-full" defaultValue="USER">
<option value="USER">User</option>
<option value="ADMIN">Admin</option>
</select>
</div>
<div className="flex gap-2 justify-end">
<button type="button" onClick={() => setAddUserModalOpen(false)} className="px-4 py-2 border rounded hover:bg-gray-100">
Cancel
</button>
<button type="submit" disabled={addUserMutate.isPending} className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50">
{addUserMutate.isPending ? "Adding..." : "Add User"}
</button>
</div>
</form>
</div>
</div>
)}
{/* Edit password modal */}
{editPasswordUser && (
<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">Change password for {editPasswordUser.username}</h2>
<form
onSubmit={(e) => {
e.preventDefault();
const form = e.currentTarget;
const password = (form.querySelector('[name="edit-password"]') as HTMLInputElement)?.value;
if (!password?.trim()) {
toast({ title: "Error", description: "Password is required.", variant: "destructive" });
return;
}
updateUserPasswordMutate.mutate({ id: editPasswordUser.id, password });
}}
className="space-y-4"
>
<div>
<label className="block text-sm font-medium">New password</label>
<input name="edit-password" type="password" required className="mt-1 p-2 border rounded w-full" placeholder="••••••••" />
</div>
<div className="flex gap-2 justify-end">
<button type="button" onClick={() => setEditPasswordUser(null)} className="px-4 py-2 border rounded hover:bg-gray-100">
Cancel
</button>
<button type="submit" disabled={updateUserPasswordMutate.isPending} className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50">
{updateUserPasswordMutate.isPending ? "Saving..." : "Save"}
</button>
</div>
</form>
</div>
</div>
)}
<DeleteConfirmationDialog
isOpen={!!userToDelete}
onConfirm={() => userToDelete && deleteUserMutate.mutate(userToDelete.id)}
onCancel={() => setUserToDelete(null)}
entityName={userToDelete?.username}
/>
{/* Credential Section */}
<div className="mt-6">
<CredentialTable />