fix: resolve audit report gaps across bulk imports, auth, scoping, and exports

This commit is contained in:
Atharv1705
2026-11-16 13:03:41 +05:30
parent ee9390a2a0
commit f356442900
25 changed files with 1994 additions and 45 deletions
@@ -0,0 +1,403 @@
import { useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import {
Download,
FileSpreadsheet,
Upload,
CheckCircle2,
AlertCircle,
X,
} from "lucide-react";
import type { BulkImportResult } from "@/api/assets";
import { ApiError } from "@/api/client";
import { Modal } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
export interface PreviewColumn {
key: string;
label: string;
}
interface BulkGenericImportModalProps {
open: boolean;
onClose: () => void;
title: string;
description: string;
entityName: string;
templateFilename: string;
onDownloadTemplate: () => Promise<void>;
onImport: (file: File, dryRun: boolean, skipInvalid: boolean) => Promise<BulkImportResult>;
queryKeysToInvalidate: string[][];
previewColumns: PreviewColumn[];
}
const ACCEPTED_EXTS = [".xlsx", ".xls", ".csv"];
export function BulkGenericImportModal({
open,
onClose,
title,
description,
entityName,
templateFilename,
onDownloadTemplate,
onImport,
queryKeysToInvalidate,
previewColumns,
}: BulkGenericImportModalProps) {
const qc = useQueryClient();
const fileInputRef = useRef<HTMLInputElement>(null);
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [dragActive, setDragActive] = useState(false);
const [downloadingTemplate, setDownloadingTemplate] = useState(false);
const [validating, setValidating] = useState(false);
const [importing, setImporting] = useState(false);
const [skipInvalid, setSkipInvalid] = useState(false);
const [preview, setPreview] = useState<BulkImportResult | null>(null);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
function resetState() {
setSelectedFile(null);
setPreview(null);
setErrorMsg(null);
setSkipInvalid(false);
setValidating(false);
setImporting(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
function handleClose() {
if (importing) return;
resetState();
onClose();
}
async function handleDownloadTemplate() {
setDownloadingTemplate(true);
setErrorMsg(null);
try {
await onDownloadTemplate();
toast.success(`Downloaded ${templateFilename}`);
} catch (err) {
const msg =
err instanceof ApiError
? err.detail
: "Failed to download import template.";
setErrorMsg(msg);
toast.error(msg);
} finally {
setDownloadingTemplate(false);
}
}
async function handleFileSelect(files: FileList | null) {
if (!files || files.length === 0) return;
const file = files[0];
const lower = file.name.toLowerCase();
if (!ACCEPTED_EXTS.some((ext) => lower.endsWith(ext))) {
setErrorMsg("Unsupported file type. Please upload an .xlsx, .xls, or .csv file.");
setSelectedFile(null);
setPreview(null);
return;
}
setSelectedFile(file);
setErrorMsg(null);
setPreview(null);
setSkipInvalid(false);
setValidating(true);
try {
const result = await onImport(file, true, false);
setPreview(result);
} catch (err) {
const msg =
err instanceof ApiError
? err.detail
: "Failed to validate import file.";
setErrorMsg(msg);
} finally {
setValidating(false);
}
}
async function handleConfirmImport() {
if (!selectedFile || !preview) return;
setImporting(true);
setErrorMsg(null);
try {
const result = await onImport(selectedFile, false, skipInvalid);
await Promise.all(
queryKeysToInvalidate.map((key) => qc.invalidateQueries({ queryKey: key }))
);
toast.success(
`Imported ${result.created_count} ${entityName.toLowerCase()}${
result.created_count === 1 ? "" : "s"
}`
);
resetState();
onClose();
} catch (err) {
const msg =
err instanceof ApiError ? err.detail : `Bulk ${entityName.toLowerCase()} import failed.`;
setErrorMsg(msg);
toast.error(msg);
} finally {
setImporting(false);
}
}
const canImport =
Boolean(selectedFile && preview) &&
!validating &&
!importing &&
preview!.valid_count > 0 &&
(preview!.error_count === 0 || skipInvalid);
return (
<Modal
open={open}
onOpenChange={(next) => {
if (!next) handleClose();
}}
title={title}
description={description}
className="max-w-4xl"
>
<div className="space-y-4">
{/* Step 1: Template Download */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 rounded-lg border border-blue-200 bg-blue-50/70 p-3.5">
<div className="flex items-start gap-2.5 text-xs text-blue-950">
<FileSpreadsheet className="h-5 w-5 text-[#1e3a8a] shrink-0 mt-0.5" />
<div>
<div className="font-semibold text-sm text-[#1e3a8a]">
Step 1: Download the Excel Template
</div>
<p className="mt-0.5 text-blue-900/90">
Download the official pre-formatted template with lookup references before uploading.
</p>
</div>
</div>
<Button
type="button"
variant="outline"
size="sm"
loading={downloadingTemplate}
onClick={handleDownloadTemplate}
className="shrink-0 bg-white"
>
<Download className="h-4 w-4 mr-1.5" />
Download Template (.xlsx)
</Button>
</div>
{/* Step 2: File Picker / Dropzone */}
<div
onDragOver={(e) => {
e.preventDefault();
setDragActive(true);
}}
onDragLeave={() => setDragActive(false)}
onDrop={(e) => {
e.preventDefault();
setDragActive(false);
void handleFileSelect(e.dataTransfer.files);
}}
className={cn(
"border-2 border-dashed rounded-lg p-5 text-center transition-colors",
dragActive
? "border-[#1e3a8a] bg-blue-50"
: "border-gray-300 bg-gray-50/60 hover:bg-gray-50"
)}
>
<input
ref={fileInputRef}
type="file"
accept=".xlsx,.xls,.csv"
aria-label={`Upload ${entityName.toLowerCase()} spreadsheet`}
onChange={(e) => void handleFileSelect(e.target.files)}
className="hidden"
/>
<Upload className="h-7 w-7 text-gray-400 mx-auto mb-2" />
<p className="text-sm font-medium text-gray-800">
{selectedFile ? selectedFile.name : "Drop your spreadsheet here, or browse"}
</p>
<p className="text-xs text-gray-500 mt-1">
Accepts <code>.xlsx</code>, <code>.xls</code>, or <code>.csv</code> — automatically validates rows before importing.
</p>
<div className="mt-3 flex items-center justify-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
disabled={validating || importing}
onClick={() => fileInputRef.current?.click()}
>
{selectedFile ? "Choose Another File" : "Select Spreadsheet"}
</Button>
{selectedFile && (
<Button
type="button"
variant="ghost"
size="sm"
disabled={validating || importing}
onClick={resetState}
>
<X className="h-3.5 w-3.5 mr-1" />
Clear
</Button>
)}
</div>
</div>
{validating && (
<div className="rounded-md border border-blue-200 bg-blue-50 px-3.5 py-2.5 text-xs text-blue-900">
Validating rows against hospital masters...
</div>
)}
{errorMsg && (
<div
role="alert"
className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800"
>
<AlertCircle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />
<span>{errorMsg}</span>
</div>
)}
{/* Step 3: Dry-run Validation Preview */}
{preview && (
<div className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex flex-wrap items-center gap-2">
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700 border border-gray-200">
Total Rows: {preview.total_rows}
</span>
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
<CheckCircle2 className="h-3.5 w-3.5" />
Valid: {preview.valid_count}
</span>
<span
className={cn(
"inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium border",
preview.error_count > 0
? "bg-red-100 text-red-800 border-red-200"
: "bg-gray-100 text-gray-600 border-gray-200"
)}
>
<AlertCircle className="h-3.5 w-3.5" />
Errors: {preview.error_count}
</span>
</div>
{preview.error_count > 0 && preview.valid_count > 0 && (
<label className="inline-flex items-center gap-2 text-xs font-medium text-gray-700 cursor-pointer">
<input
type="checkbox"
checked={skipInvalid}
onChange={(e) => setSkipInvalid(e.target.checked)}
className="rounded border-gray-300 text-[#1e3a8a] focus:ring-blue-500"
/>
Skip invalid rows and import valid rows only
</label>
)}
</div>
<div className="border border-gray-200 rounded-lg overflow-hidden">
<div className="max-h-64 overflow-auto">
<table className="w-full text-xs">
<thead className="bg-gray-50 border-b border-gray-200 sticky top-0">
<tr>
<th className="px-3 py-2 text-left font-medium text-gray-600">Row</th>
{previewColumns.map((col) => (
<th key={col.key} className="px-3 py-2 text-left font-medium text-gray-600">
{col.label}
</th>
))}
<th className="px-3 py-2 text-left font-medium text-gray-600">Validation</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 bg-white">
{preview.preview_rows.length === 0 ? (
<tr>
<td
colSpan={previewColumns.length + 2}
className="px-3 py-6 text-center text-gray-400"
>
No data rows found in spreadsheet.
</td>
</tr>
) : (
preview.preview_rows.map((r) => {
const rowRecord = r as unknown as Record<string, unknown>;
const rowData = (rowRecord.data as Record<string, unknown> | undefined) || rowRecord;
return (
<tr
key={r.row}
className={r.valid ? "bg-white" : "bg-red-50/60"}
>
<td className="px-3 py-2 font-mono text-gray-500">{r.row}</td>
{previewColumns.map((col) => {
const val = rowRecord[col.key] ?? rowData[col.key];
return (
<td key={col.key} className="px-3 py-2 text-gray-800">
{val !== null && val !== undefined && val !== ""
? String(val)
: "—"}
</td>
);
})}
<td className="px-3 py-2">
{r.valid ? (
<span className="inline-flex items-center gap-1 text-green-700 font-medium">
<CheckCircle2 className="h-3.5 w-3.5" />
Ready
</span>
) : (
<span className="inline-flex items-start gap-1 text-red-700">
<AlertCircle className="h-3.5 w-3.5 shrink-0 mt-0.5" />
<span>{r.error || "Invalid row"}</span>
</span>
)}
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
</div>
</div>
)}
{/* Footer */}
<div className="flex flex-col-reverse sm:flex-row sm:items-center justify-end gap-2 pt-2 border-t border-gray-100">
<Button
type="button"
variant="outline"
size="sm"
disabled={importing}
onClick={handleClose}
>
Cancel
</Button>
<Button
type="button"
size="sm"
loading={importing}
disabled={!canImport}
onClick={handleConfirmImport}
>
<Upload className="h-4 w-4 mr-1.5" />
Import {preview?.valid_count ?? 0} {entityName}
</Button>
</div>
</div>
</Modal>
);
}
@@ -0,0 +1,174 @@
import { useState } from "react";
import { KeyRound, AlertCircle, Eye, EyeOff } from "lucide-react";
import { changePasswordApi } from "@/api/auth";
import { ApiError } from "@/api/client";
import { Modal } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { toast } from "@/lib/toast";
interface ChangePasswordModalProps {
open: boolean;
onClose: () => void;
}
export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps) {
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [showCurrent, setShowCurrent] = useState(false);
const [showNew, setShowNew] = useState(false);
const [loading, setLoading] = useState(false);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
function resetState() {
setCurrentPassword("");
setNewPassword("");
setConfirmPassword("");
setShowCurrent(false);
setShowNew(false);
setErrorMsg(null);
}
function handleClose() {
if (loading) return;
resetState();
onClose();
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setErrorMsg(null);
if (!currentPassword) {
setErrorMsg("Please enter your current password.");
return;
}
if (!newPassword || newPassword.length < 6) {
setErrorMsg("New password must be at least 6 characters.");
return;
}
if (newPassword !== confirmPassword) {
setErrorMsg("New passwords do not match.");
return;
}
setLoading(true);
try {
const res = await changePasswordApi(currentPassword, newPassword);
toast.success(res.message || "Password changed successfully.");
handleClose();
} catch (err) {
const msg =
err instanceof ApiError ? err.detail : "Failed to change password.";
setErrorMsg(msg);
} finally {
setLoading(false);
}
}
return (
<Modal
open={open}
onOpenChange={(next) => {
if (!next) handleClose();
}}
title="Change Password"
description="Update your account login password. Password must be at least 6 characters long."
className="max-w-md"
>
<form onSubmit={handleSubmit} className="space-y-4">
{errorMsg && (
<div
role="alert"
className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800"
>
<AlertCircle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />
<span>{errorMsg}</span>
</div>
)}
<div className="space-y-1">
<label className="text-xs font-medium text-gray-700">
Current Password <span className="text-red-500">*</span>
</label>
<div className="relative">
<input
type={showCurrent ? "text" : "password"}
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
required
autoComplete="current-password"
placeholder="Enter current password"
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md pr-10 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<button
type="button"
onClick={() => setShowCurrent((s) => !s)}
className="absolute right-2.5 top-2.5 text-gray-400 hover:text-gray-600"
aria-label={showCurrent ? "Hide current password" : "Show current password"}
>
{showCurrent ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
</div>
<div className="space-y-1">
<label className="text-xs font-medium text-gray-700">
New Password <span className="text-red-500">*</span>
</label>
<div className="relative">
<input
type={showNew ? "text" : "password"}
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
required
minLength={6}
autoComplete="new-password"
placeholder="At least 6 characters"
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md pr-10 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<button
type="button"
onClick={() => setShowNew((s) => !s)}
className="absolute right-2.5 top-2.5 text-gray-400 hover:text-gray-600"
aria-label={showNew ? "Hide new password" : "Show new password"}
>
{showNew ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
</div>
<div className="space-y-1">
<label className="text-xs font-medium text-gray-700">
Confirm New Password <span className="text-red-500">*</span>
</label>
<input
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
autoComplete="new-password"
placeholder="Re-enter new password"
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div className="flex items-center justify-end gap-2 pt-3 border-t border-gray-100">
<Button
type="button"
variant="outline"
size="sm"
disabled={loading}
onClick={handleClose}
>
Cancel
</Button>
<Button type="submit" size="sm" loading={loading}>
<KeyRound className="h-4 w-4 mr-1.5" />
Update Password
</Button>
</div>
</form>
</Modal>
);
}
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { ColumnDef } from "@tanstack/react-table";
import XLSX from "xlsx-js-style";
import { DataTable } from "./DataTable";
@@ -38,7 +38,7 @@ describe("DataTable", () => {
vi.clearAllMocks();
});
it("renders rows, filters globally, and exports visible rows to Excel (.xlsx)", () => {
it("renders rows, filters globally, and exports visible rows to Excel (.xlsx)", async () => {
render(
<DataTable
data={data}
@@ -62,10 +62,12 @@ describe("DataTable", () => {
expect(exportBtn).toHaveTextContent("Export Excel (.xlsx)");
fireEvent.click(exportBtn);
expect(XLSX.writeFile).toHaveBeenCalledTimes(1);
expect(XLSX.writeFile).toHaveBeenCalledWith(
expect.objectContaining({ SheetNames: ["Data"] }),
"test-assets.xlsx"
);
await waitFor(() => {
expect(XLSX.writeFile).toHaveBeenCalledTimes(1);
expect(XLSX.writeFile).toHaveBeenCalledWith(
expect.objectContaining({ SheetNames: ["Data"] }),
"test-assets.xlsx"
);
});
});
});
@@ -14,7 +14,6 @@ import {
type Table as TanStackTable,
} from "@tanstack/react-table";
import { useState } from "react";
import XLSX from "xlsx-js-style";
import {
ChevronUp,
ChevronDown,
@@ -46,7 +45,7 @@ function formatExcelCell(val: unknown): string | number {
return JSON.stringify(val);
}
function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
async function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
const rows = table.getPrePaginationRowModel().rows;
if (!rows.length) return;
@@ -55,6 +54,9 @@ function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
.filter((col) => col.id !== "actions");
if (!visibleCols.length) return;
const XLSXModule = await import("xlsx-js-style");
const XLSX = XLSXModule.default ?? XLSXModule;
const exportRows = rows.map((row) => {
const record: Record<string, string | number> = {};
for (const col of visibleCols) {
+20
View File
@@ -18,6 +18,7 @@ import {
X,
Package,
AlertCircle,
KeyRound,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { formatDate, formatRelative } from "@/lib/format";
@@ -28,6 +29,7 @@ import { notificationsApi, type NotificationItem } from "@/api/notifications";
import { searchApi } from "@/api/search";
import { Badge } from "@/components/ui/badge";
import { AssetStatusBadge, CallStatusBadge } from "@/components/StatusBadge";
import { ChangePasswordModal } from "@/components/ChangePasswordModal";
import { toast } from "@/lib/toast";
interface TopBarProps {
@@ -41,6 +43,7 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
const [menuOpen, setMenuOpen] = useState(false);
const [changePasswordOpen, setChangePasswordOpen] = useState(false);
const [bellOpen, setBellOpen] = useState(false);
const [dateInput, setDateInput] = useState(demoAsOfDate ?? "");
const [savingDate, setSavingDate] = useState(false);
@@ -233,6 +236,7 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
}
return (
<>
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-3 sm:px-4 py-2 gap-2 sm:gap-3 sticky top-0 z-10">
{/* Mobile/tablet nav toggle */}
{onMenuClick && (
@@ -598,6 +602,17 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
)}
</div>
</div>
<button
type="button"
onClick={() => {
setMenuOpen(false);
setChangePasswordOpen(true);
}}
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 text-left"
>
<KeyRound className="h-4 w-4 text-gray-500" />
Change Password
</button>
<button
type="button"
onClick={handleSignOut}
@@ -611,6 +626,11 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
</div>
</div>
</header>
<ChangePasswordModal
open={changePasswordOpen}
onClose={() => setChangePasswordOpen(false)}
/>
</>
);
}