269 lines
8.9 KiB
TypeScript
269 lines
8.9 KiB
TypeScript
import { useState, useRef } from "react";
|
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
import {
|
|
Upload,
|
|
FileText,
|
|
Image as ImageIcon,
|
|
Download,
|
|
Trash2,
|
|
AlertCircle,
|
|
ExternalLink,
|
|
} from "lucide-react";
|
|
import {
|
|
attachmentsApi,
|
|
type AttachmentEntityType,
|
|
type AttachmentItem,
|
|
} from "@/api/attachments";
|
|
import { ApiError } from "@/api/client";
|
|
import { formatDateTime } from "@/lib/format";
|
|
import { validateAttachmentFile } from "@/lib/validation";
|
|
import { Button } from "@/components/ui/button";
|
|
|
|
function formatBytes(bytes: number): string {
|
|
if (bytes < 1024) return `${bytes} B`;
|
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
|
}
|
|
|
|
interface AttachmentsProps {
|
|
entityType: AttachmentEntityType;
|
|
entityId: number;
|
|
canUpload: boolean;
|
|
canDelete: boolean;
|
|
}
|
|
|
|
export function Attachments({
|
|
entityType,
|
|
entityId,
|
|
canUpload,
|
|
canDelete,
|
|
}: AttachmentsProps) {
|
|
const qc = useQueryClient();
|
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
|
const [dragActive, setDragActive] = useState(false);
|
|
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
|
const [confirmDeleteId, setConfirmDeleteId] = useState<number | null>(null);
|
|
|
|
const queryKey = ["attachments", entityType, entityId];
|
|
|
|
const { data, isLoading } = useQuery({
|
|
queryKey,
|
|
queryFn: () => attachmentsApi.list(entityType, entityId),
|
|
enabled: Boolean(entityId),
|
|
});
|
|
|
|
const uploadMutation = useMutation({
|
|
mutationFn: (file: File) => attachmentsApi.upload(entityType, entityId, file),
|
|
onSuccess: () => {
|
|
setErrorMsg(null);
|
|
qc.invalidateQueries({ queryKey });
|
|
if (entityType === "asset") {
|
|
qc.invalidateQueries({ queryKey: ["asset-overview", entityId] });
|
|
}
|
|
},
|
|
onError: (err) => {
|
|
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to upload attachment.");
|
|
},
|
|
});
|
|
|
|
const deleteMutation = useMutation({
|
|
mutationFn: (id: number) => attachmentsApi.remove(id),
|
|
onSuccess: () => {
|
|
setConfirmDeleteId(null);
|
|
setErrorMsg(null);
|
|
qc.invalidateQueries({ queryKey });
|
|
if (entityType === "asset") {
|
|
qc.invalidateQueries({ queryKey: ["asset-overview", entityId] });
|
|
}
|
|
},
|
|
onError: (err) => {
|
|
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to delete attachment.");
|
|
},
|
|
});
|
|
|
|
function handleFiles(files: FileList | null) {
|
|
if (!files || files.length === 0) return;
|
|
const file = files[0];
|
|
const validationError = validateAttachmentFile(file);
|
|
if (validationError) {
|
|
setErrorMsg(validationError);
|
|
return;
|
|
}
|
|
setErrorMsg(null);
|
|
uploadMutation.mutate(file);
|
|
}
|
|
|
|
async function handleDownload(att: AttachmentItem, preview = false) {
|
|
try {
|
|
setErrorMsg(null);
|
|
await attachmentsApi.download(att.id, att.original_name, preview);
|
|
} catch (err) {
|
|
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to download file.");
|
|
}
|
|
}
|
|
|
|
const items = data?.items ?? [];
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
{errorMsg && (
|
|
<div
|
|
role="alert"
|
|
className="flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
|
>
|
|
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
|
<span>{errorMsg}</span>
|
|
</div>
|
|
)}
|
|
|
|
{canUpload && (
|
|
<div
|
|
onDragOver={(e) => {
|
|
e.preventDefault();
|
|
setDragActive(true);
|
|
}}
|
|
onDragLeave={() => setDragActive(false)}
|
|
onDrop={(e) => {
|
|
e.preventDefault();
|
|
setDragActive(false);
|
|
handleFiles(e.dataTransfer.files);
|
|
}}
|
|
className={`border-2 border-dashed rounded-lg p-5 text-center transition-colors ${
|
|
dragActive
|
|
? "border-[#1e3a8a] bg-blue-50/50"
|
|
: "border-gray-300 bg-gray-50/50 hover:border-gray-400"
|
|
}`}
|
|
>
|
|
<input
|
|
ref={fileInputRef}
|
|
type="file"
|
|
accept=".jpg,.jpeg,.png,.pdf"
|
|
aria-label="Upload attachment"
|
|
className="hidden"
|
|
onChange={(e) => {
|
|
handleFiles(e.target.files);
|
|
e.target.value = "";
|
|
}}
|
|
/>
|
|
<Upload className="h-6 w-6 text-gray-400 mx-auto mb-2" />
|
|
<p className="text-sm text-gray-600">
|
|
Drag and drop a file here, or{" "}
|
|
<button
|
|
type="button"
|
|
onClick={() => fileInputRef.current?.click()}
|
|
disabled={uploadMutation.isPending}
|
|
className="text-[#1e3a8a] font-medium hover:underline disabled:opacity-50"
|
|
>
|
|
browse
|
|
</button>
|
|
</p>
|
|
<p className="text-xs text-gray-400 mt-1">
|
|
Allowed: JPG, PNG, PDF • Max size: 10 MB
|
|
</p>
|
|
{uploadMutation.isPending && (
|
|
<p className="text-xs text-blue-600 mt-2">Uploading...</p>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{isLoading ? (
|
|
<div className="space-y-2">
|
|
{[1, 2].map((i) => (
|
|
<div key={i} className="h-14 bg-gray-100 rounded-md animate-pulse" />
|
|
))}
|
|
</div>
|
|
) : items.length === 0 ? (
|
|
<div className="text-sm text-gray-400 py-6 text-center border border-gray-200 rounded-lg bg-white">
|
|
No attachments uploaded yet.
|
|
</div>
|
|
) : (
|
|
<div className="bg-white border border-gray-200 rounded-lg divide-y divide-gray-100">
|
|
{items.map((att) => {
|
|
const isPdf = att.mime_type === "application/pdf";
|
|
return (
|
|
<div
|
|
key={att.id}
|
|
className="flex items-center justify-between gap-3 px-4 py-3 hover:bg-gray-50/60"
|
|
>
|
|
<div className="flex items-center gap-3 min-w-0">
|
|
<div className="h-9 w-9 rounded-md bg-blue-50 text-[#1e3a8a] flex items-center justify-center shrink-0">
|
|
{isPdf ? <FileText className="h-5 w-5" /> : <ImageIcon className="h-5 w-5" />}
|
|
</div>
|
|
<div className="min-w-0">
|
|
<div className="text-sm font-medium text-gray-900 truncate">
|
|
{att.original_name}
|
|
</div>
|
|
<div className="text-xs text-gray-500">
|
|
{formatBytes(att.size_bytes)}
|
|
{att.uploaded_by_name ? ` • Uploaded by ${att.uploaded_by_name}` : ""}
|
|
{" • "}
|
|
{formatDateTime(att.uploaded_at)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-1.5 shrink-0">
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => handleDownload(att, true)}
|
|
title="Preview in new tab"
|
|
>
|
|
<ExternalLink className="h-3.5 w-3.5 mr-1" />
|
|
Preview
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => handleDownload(att, false)}
|
|
title="Download file"
|
|
>
|
|
<Download className="h-3.5 w-3.5 mr-1" />
|
|
Download
|
|
</Button>
|
|
{canDelete && (
|
|
confirmDeleteId === att.id ? (
|
|
<div className="flex items-center gap-1">
|
|
<Button
|
|
type="button"
|
|
variant="danger"
|
|
size="sm"
|
|
loading={deleteMutation.isPending}
|
|
onClick={() => deleteMutation.mutate(att.id)}
|
|
>
|
|
Confirm
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={() => setConfirmDeleteId(null)}
|
|
>
|
|
Cancel
|
|
</Button>
|
|
</div>
|
|
) : (
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="sm"
|
|
className="text-red-600 hover:bg-red-50"
|
|
onClick={() => setConfirmDeleteId(att.id)}
|
|
aria-label={`Delete ${att.original_name}`}
|
|
>
|
|
<Trash2 className="h-3.5 w-3.5" />
|
|
</Button>
|
|
)
|
|
)}
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|