insuranceCred half

This commit is contained in:
2025-06-02 21:49:37 +05:30
parent e147481215
commit 8945e56f14
9 changed files with 509 additions and 25 deletions

View File

@@ -0,0 +1,113 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { toast } from "@/hooks/use-toast";
type CredentialFormProps = {
onClose: () => void;
userId: number;
};
export function CredentialForm({ onClose, userId }: CredentialFormProps) {
const [siteKey, setSiteKey] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const queryClient = useQueryClient();
const createCredentialMutation = useMutation({
mutationFn: async () => {
const payload = {
siteKey: siteKey.trim(),
username: username.trim(),
password: password.trim(),
userId,
};
const res = await apiRequest("POST", "/api/insuranceCreds/", payload);
if (!res.ok) {
const errorData = await res.json().catch(() => null);
throw new Error(errorData?.message || "Failed to create credential");
}
return res.json();
},
onSuccess: () => {
toast({ title: "Credential created." });
queryClient.invalidateQueries({ queryKey: ["/api/insuranceCreds/"] });
onClose();
},
onError: (error: any) => {
toast({
title: "Error",
description: error.message || "Unknown error",
variant: "destructive",
});
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!siteKey || !username || !password) {
toast({
title: "Error",
description: "All fields are required.",
variant: "destructive",
});
return;
}
createCredentialMutation.mutate();
};
return (
<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">Create Credential</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium">Site Key</label>
<input
type="text"
value={siteKey}
onChange={(e) => setSiteKey(e.target.value)}
className="mt-1 p-2 border rounded w-full"
placeholder="e.g., github, slack"
/>
</div>
<div>
<label className="block text-sm font-medium">Username</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="mt-1 p-2 border rounded w-full"
/>
</div>
<div>
<label className="block text-sm font-medium">Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="mt-1 p-2 border rounded w-full"
/>
</div>
<div className="flex justify-end gap-2">
<button
type="button"
onClick={onClose}
className="text-gray-600 hover:underline"
>
Cancel
</button>
<button
type="submit"
disabled={createCredentialMutation.isPending}
className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
>
{createCredentialMutation.isPending ? "Creating..." : "Create"}
</button>
</div>
</form>
</div>
</div>
);
}

View File

@@ -0,0 +1,57 @@
// components/CredentialTable.tsx
import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { toast } from "@/hooks/use-toast";
type Credential = {
id: number;
siteKey: string;
username: string;
password: string;
};
export function CredentialTable() {
const { data, isLoading, error } = useQuery({
queryKey: ["/api/credentials/"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/insuranceCreds/");
if (!res.ok) {
throw new Error("Failed to fetch credentials");
}
return res.json() as Promise<Credential[]>;
},
});
if (isLoading) return <p className="text-gray-600">Loading credentials...</p>;
if (error) return <p className="text-red-600">Failed to load credentials.</p>;
if (!data || data.length === 0)
return <p className="text-gray-600">No credentials found.</p>;
return (
<div className="overflow-x-auto">
<table className="min-w-full border rounded shadow">
<thead className="bg-gray-100">
<tr>
<th className="px-4 py-2 text-left">Site</th>
<th className="px-4 py-2 text-left">Username</th>
<th className="px-4 py-2 text-left">Password</th>
<th className="px-4 py-2 text-right">Actions</th>
</tr>
</thead>
<tbody>
{data.map((cred) => (
<tr key={cred.id} className="border-t">
<td className="px-4 py-2">{cred.siteKey}</td>
<td className="px-4 py-2">{cred.username}</td>
<td className="px-4 py-2 font-mono">{cred.password}</td>
<td className="px-4 py-2 text-right space-x-2">
<button className="text-blue-600 hover:underline">Edit</button>
<button className="text-red-600 hover:underline">Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}

View File

@@ -10,6 +10,8 @@ import { z } from "zod";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { StaffForm } from "@/components/staffs/staff-form";
import { DeleteConfirmationDialog } from "@/components/ui/deleteDialog";
import { CredentialForm } from "@/components/settings/InsuranceCredForm";
import { CredentialTable } from "@/components/settings/insuranceCredTable";
// Correctly infer Staff type from zod schema
type Staff = z.infer<typeof StaffUncheckedCreateInputObjectSchema>;
@@ -20,6 +22,7 @@ export default function SettingsPage() {
// 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);
@@ -121,7 +124,7 @@ export default function SettingsPage() {
return id;
},
onSuccess: () => {
setIsDeleteStaffOpen(false);
setIsDeleteStaffOpen(false);
queryClient.invalidateQueries({ queryKey: ["/api/staffs/"] });
toast({
title: "Staff Removed",
@@ -217,6 +220,68 @@ export default function SettingsPage() {
`Viewing staff member:\n${staff.name} (${staff.email || "No email"})`
);
// MANAGE USER
const [usernameUser, setUsernameUser] = useState("");
//fetch user
const {
data: currentUser,
isLoading: isUserLoading,
isError: isUserError,
error: userError,
} = useQuery({
queryKey: ["/api/users/"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/users/");
if (!res.ok) throw new Error("Failed to fetch user");
return res.json();
},
});
// Populate fields after fetch
useEffect(() => {
if (currentUser) {
setUsernameUser(currentUser.username);
}
}, [currentUser]);
//update user mutation
const updateUserMutate = useMutation({
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");
}
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",
});
},
});
return (
<div className="flex h-screen overflow-hidden bg-gray-100">
<Sidebar
@@ -270,6 +335,95 @@ export default function SettingsPage() {
</div>
</div>
)}
<Card className="mt-6">
<CardContent className="space-y-4 py-6">
<h3 className="text-lg font-semibold">User Settings</h3>
{isUserLoading ? (
<p>Loading user...</p>
) : isUserError ? (
<p className="text-red-500">{(userError as Error)?.message}</p>
) : (
<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({
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"
/>
</div>
<div>
<label className="block text-sm font-medium">
New Password
</label>
<input
type="password"
name="password"
className="mt-1 p-2 border rounded w-full"
placeholder="••••••••"
/>
<p className="text-xs text-gray-500 mt-1">
Leave blank to keep current password.
</p>
</div>
<button
type="submit"
className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
disabled={updateUserMutate.isPending}
>
{updateUserMutate.isPending ? "Saving..." : "Save Changes"}
</button>
</form>
)}
</CardContent>
</Card>
{/* Credential Section */}
<div className="mt-8">
<button
onClick={() => setCredentialModalOpen(true)}
className="mb-4 bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700"
>
Add Credential
</button>
<Card>
<CardContent>
<h3 className="text-lg font-semibold mb-4">Saved Credentials</h3>
<CredentialTable />
</CardContent>
</Card>
</div>
{credentialModalOpen && currentUser?.id && (
<CredentialForm
userId={currentUser.id}
onClose={() => setCredentialModalOpen(false)}
/>
)}
</main>
</div>
</div>