fix: resolve audit report gaps across bulk imports, auth, scoping, and exports
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user