fix(task5): add admin reset-password dialog in masters page
This commit is contained in:
@@ -153,6 +153,8 @@ export const usersApi = {
|
||||
}>
|
||||
) => api.patch<MasterUser>(`/users/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/users/${id}`),
|
||||
resetPassword: (id: number, new_password: string) =>
|
||||
api.post<{ message: string }>(`/users/${id}/reset-password`, { new_password }),
|
||||
};
|
||||
|
||||
export interface UserLookupItem {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { api } from "./client";
|
||||
import { usersApi } from "./masters";
|
||||
|
||||
export { usersApi };
|
||||
|
||||
export const resetPassword = (id: number, new_password: string) =>
|
||||
api.post<{ message: string }>(`/users/${id}/reset-password`, { new_password });
|
||||
@@ -1,16 +1,18 @@
|
||||
import { useState, useMemo } from "react";
|
||||
import { useState, useMemo, useEffect } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Plus, Pencil, Power, AlertCircle } from "lucide-react";
|
||||
import { Plus, Pencil, Power, AlertCircle, KeyRound, Eye, EyeOff } from "lucide-react";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { ROLE_LABELS, type Role } from "@/lib/permissions";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { toast } from "@/lib/toast";
|
||||
import {
|
||||
departmentsApi,
|
||||
locationsApi,
|
||||
@@ -542,6 +544,113 @@ function UserModal({
|
||||
);
|
||||
}
|
||||
|
||||
export function ResetPasswordModal({
|
||||
user,
|
||||
onClose,
|
||||
}: {
|
||||
user: MasterUser | null;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [clientError, setClientError] = useState<string | null>(null);
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setNewPassword("");
|
||||
setConfirmPassword("");
|
||||
setShowPassword(false);
|
||||
setClientError(null);
|
||||
setServerError(null);
|
||||
}, [user]);
|
||||
|
||||
if (!user) return null;
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!user) return;
|
||||
setClientError(null);
|
||||
setServerError(null);
|
||||
|
||||
if (newPassword !== confirmPassword) {
|
||||
setClientError("Passwords do not match");
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await usersApi.resetPassword(user.id, newPassword);
|
||||
toast.success(`Password for ${user.name} has been reset.`);
|
||||
setNewPassword("");
|
||||
setConfirmPassword("");
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setServerError(err instanceof ApiError ? err.detail : "Failed to reset password.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={Boolean(user)}
|
||||
onOpenChange={(open) => !open && onClose()}
|
||||
title={`Reset Password for ${user.name}`}
|
||||
>
|
||||
<FormErrorBanner message={clientError || serverError} />
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className={labelCls}>New Password *</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showPassword ? "text" : "password"}
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
required
|
||||
className={inputCls}
|
||||
placeholder="Enter new password"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword((s) => !s)}
|
||||
className="absolute right-2.5 top-2.5 text-gray-400 hover:text-gray-600"
|
||||
aria-label={showPassword ? "Hide password" : "Show password"}
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-1">At least 8 characters, with a letter and a number.</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Confirm Password *</label>
|
||||
<input
|
||||
type={showPassword ? "text" : "password"}
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
required
|
||||
className={inputCls}
|
||||
placeholder="Re-enter new password"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2 border-t border-gray-100">
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={submitting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
Reset Password
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Main MastersPage ---
|
||||
export function MastersPage() {
|
||||
const qc = useQueryClient();
|
||||
@@ -554,6 +663,8 @@ export function MastersPage() {
|
||||
const [editingCat, setEditingCat] = useState<Category | null>(null);
|
||||
const [editingVendor, setEditingVendor] = useState<Vendor | null>(null);
|
||||
const [editingUser, setEditingUser] = useState<MasterUser | null>(null);
|
||||
const [resetPasswordUser, setResetPasswordUser] = useState<MasterUser | null>(null);
|
||||
const { user: currentUser } = useAuthStore();
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", includeInactive],
|
||||
@@ -806,17 +917,30 @@ export function MastersPage() {
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<RowActions
|
||||
active={row.original.is_active}
|
||||
busy={toggleMutation.isPending}
|
||||
onEdit={() => {
|
||||
setEditingUser(row.original);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
onToggleActive={() =>
|
||||
toggleMutation.mutate({ tab: "users", id: row.original.id, currentlyActive: row.original.is_active })
|
||||
}
|
||||
/>
|
||||
<div className="flex items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
|
||||
<RowActions
|
||||
active={row.original.is_active}
|
||||
busy={toggleMutation.isPending}
|
||||
onEdit={() => {
|
||||
setEditingUser(row.original);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
onToggleActive={() =>
|
||||
toggleMutation.mutate({ tab: "users", id: row.original.id, currentlyActive: row.original.is_active })
|
||||
}
|
||||
/>
|
||||
{currentUser?.role === "system_admin" && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setResetPasswordUser(row.original)}
|
||||
className="text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
<KeyRound className="h-3.5 w-3.5 mr-1" />
|
||||
Reset password
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
@@ -947,6 +1071,12 @@ export function MastersPage() {
|
||||
departments={activeDepartments}
|
||||
/>
|
||||
)}
|
||||
{resetPasswordUser && (
|
||||
<ResetPasswordModal
|
||||
user={resetPasswordUser}
|
||||
onClose={() => setResetPasswordUser(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { ResetPasswordModal } from "@/pages/MastersPage";
|
||||
import { usersApi, type MasterUser } from "@/api/masters";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { ApiError } from "@/api/client";
|
||||
|
||||
const mockUser: MasterUser = {
|
||||
id: 42,
|
||||
name: "Dr. Jane Doe",
|
||||
email: "jane@poona.demo",
|
||||
role: "department_user",
|
||||
department_id: 2,
|
||||
department_name: "Cardiology",
|
||||
is_active: true,
|
||||
};
|
||||
|
||||
describe("Admin ResetPasswordModal", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("renders the dialog with user details, helper text, and show/hide password toggle", () => {
|
||||
render(<ResetPasswordModal user={mockUser} onClose={vi.fn()} />);
|
||||
|
||||
expect(screen.getByText("Reset Password for Dr. Jane Doe")).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText("Enter new password")).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText("Re-enter new password")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("At least 8 characters, with a letter and a number.")
|
||||
).toBeInTheDocument();
|
||||
|
||||
const input = screen.getByPlaceholderText("Enter new password");
|
||||
expect(input).toHaveAttribute("type", "password");
|
||||
|
||||
const toggleBtn = screen.getByLabelText("Show password");
|
||||
fireEvent.click(toggleBtn);
|
||||
expect(input).toHaveAttribute("type", "text");
|
||||
expect(screen.getByLabelText("Hide password")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("validates password mismatch before calling API", async () => {
|
||||
const resetSpy = vi.spyOn(usersApi, "resetPassword").mockResolvedValue({ message: "OK" });
|
||||
|
||||
render(<ResetPasswordModal user={mockUser} onClose={vi.fn()} />);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText("Enter new password"), {
|
||||
target: { value: "SecurePass1" },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText("Re-enter new password"), {
|
||||
target: { value: "DifferentPass2" },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset Password" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/passwords do not match/i)).toBeInTheDocument();
|
||||
});
|
||||
expect(resetSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls API on match, shows success toast, and closes dialog", async () => {
|
||||
const onClose = vi.fn();
|
||||
const resetSpy = vi
|
||||
.spyOn(usersApi, "resetPassword")
|
||||
.mockResolvedValue({ message: "Password reset successfully." });
|
||||
const toastSpy = vi.spyOn(toast, "success");
|
||||
|
||||
render(<ResetPasswordModal user={mockUser} onClose={onClose} />);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText("Enter new password"), {
|
||||
target: { value: "NewSecure99" },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText("Re-enter new password"), {
|
||||
target: { value: "NewSecure99" },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset Password" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(resetSpy).toHaveBeenCalledWith(42, "NewSecure99");
|
||||
expect(toastSpy).toHaveBeenCalledWith("Password for Dr. Jane Doe has been reset.");
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("displays server error message when API returns 422 error", async () => {
|
||||
vi.spyOn(usersApi, "resetPassword").mockRejectedValue(
|
||||
new ApiError(422, "Password must not start or end with a space.")
|
||||
);
|
||||
|
||||
render(<ResetPasswordModal user={mockUser} onClose={vi.fn()} />);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText("Enter new password"), {
|
||||
target: { value: " SpacePass1 " },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText("Re-enter new password"), {
|
||||
target: { value: " SpacePass1 " },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset Password" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText("Password must not start or end with a space.")
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user