feat: Implement file upload and management features in ProjectViewPage
This commit is contained in:
@@ -4,8 +4,9 @@ import { withAdminAuth } from "@/lib/middleware/auth";
|
||||
|
||||
// GET: Get user by ID (admin only)
|
||||
async function getUserHandler(req, { params }) {
|
||||
const { id } = await params;
|
||||
try {
|
||||
const user = getUserById(params.id);
|
||||
const user = getUserById(id);
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json(
|
||||
@@ -29,9 +30,10 @@ async function getUserHandler(req, { params }) {
|
||||
|
||||
// PUT: Update user (admin only)
|
||||
async function updateUserHandler(req, { params }) {
|
||||
const { id } = await params;
|
||||
try {
|
||||
const data = await req.json();
|
||||
const userId = params.id;
|
||||
const userId = id;
|
||||
|
||||
// Prevent admin from deactivating themselves
|
||||
if (data.is_active === false && userId === req.user.id) {
|
||||
@@ -92,8 +94,9 @@ async function updateUserHandler(req, { params }) {
|
||||
|
||||
// DELETE: Delete user (admin only)
|
||||
async function deleteUserHandler(req, { params }) {
|
||||
const { id } = await params;
|
||||
try {
|
||||
const userId = params.id;
|
||||
const userId = id;
|
||||
|
||||
// Prevent admin from deleting themselves
|
||||
if (userId === req.user.id) {
|
||||
|
||||
@@ -6,9 +6,9 @@ import path from "path";
|
||||
import db from "@/lib/db";
|
||||
|
||||
export async function GET(request, { params }) {
|
||||
try {
|
||||
const fileId = params.fileId;
|
||||
const { fileId } = await params;
|
||||
|
||||
try {
|
||||
// Get file info from database
|
||||
const file = db.prepare(`
|
||||
SELECT * FROM file_attachments WHERE file_id = ?
|
||||
@@ -53,10 +53,94 @@ export async function GET(request, { params }) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request, { params }) {
|
||||
export async function PUT(request, { params }) {
|
||||
const { fileId } = await params;
|
||||
try {
|
||||
const fileId = params.fileId;
|
||||
const body = await request.json();
|
||||
const { description, original_filename } = body;
|
||||
|
||||
// Validate input
|
||||
if (description !== undefined && typeof description !== 'string') {
|
||||
return NextResponse.json(
|
||||
{ error: "Description must be a string" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (original_filename !== undefined && typeof original_filename !== 'string') {
|
||||
return NextResponse.json(
|
||||
{ error: "Original filename must be a string" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
const existingFile = db.prepare(`
|
||||
SELECT * FROM file_attachments WHERE file_id = ?
|
||||
`).get(parseInt(fileId));
|
||||
|
||||
if (!existingFile) {
|
||||
return NextResponse.json(
|
||||
{ error: "File not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Build update query
|
||||
const updates = [];
|
||||
const values = [];
|
||||
|
||||
if (description !== undefined) {
|
||||
updates.push('description = ?');
|
||||
values.push(description);
|
||||
}
|
||||
|
||||
if (original_filename !== undefined) {
|
||||
updates.push('original_filename = ?');
|
||||
values.push(original_filename);
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "No valid fields to update" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
values.push(parseInt(fileId));
|
||||
|
||||
const result = db.prepare(`
|
||||
UPDATE file_attachments
|
||||
SET ${updates.join(', ')}
|
||||
WHERE file_id = ?
|
||||
`).run(...values);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "File not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Get updated file
|
||||
const updatedFile = db.prepare(`
|
||||
SELECT * FROM file_attachments WHERE file_id = ?
|
||||
`).get(parseInt(fileId));
|
||||
|
||||
return NextResponse.json(updatedFile);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error updating file:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to update file" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request, { params }) {
|
||||
const { fileId } = await params;
|
||||
try {
|
||||
// Get file info from database
|
||||
const file = db.prepare(`
|
||||
SELECT * FROM file_attachments WHERE file_id = ?
|
||||
|
||||
@@ -110,7 +110,7 @@ async function createNoteHandler(req) {
|
||||
}
|
||||
|
||||
async function deleteNoteHandler(req, { params }) {
|
||||
const { id } = params;
|
||||
const { id } = await params;
|
||||
|
||||
// Get note data before deletion for audit log
|
||||
const note = db.prepare("SELECT * FROM notes WHERE note_id = ?").get(id);
|
||||
@@ -137,7 +137,8 @@ async function deleteNoteHandler(req, { params }) {
|
||||
}
|
||||
|
||||
async function updateNoteHandler(req, { params }) {
|
||||
const noteId = params.id;
|
||||
const { id } = await params;
|
||||
const noteId = id;
|
||||
const { note } = await req.json();
|
||||
|
||||
if (!note || !noteId) {
|
||||
|
||||
@@ -4,10 +4,11 @@ import { withReadAuth, withUserAuth } from "@/lib/middleware/auth";
|
||||
|
||||
// GET: Get a specific task template
|
||||
async function getTaskHandler(req, { params }) {
|
||||
const { id } = await params;
|
||||
try {
|
||||
const template = db
|
||||
.prepare("SELECT * FROM tasks WHERE task_id = ? AND is_standard = 1")
|
||||
.get(params.id);
|
||||
.get(id);
|
||||
|
||||
if (!template) {
|
||||
return NextResponse.json(
|
||||
@@ -27,6 +28,7 @@ async function getTaskHandler(req, { params }) {
|
||||
|
||||
// PUT: Update a task template
|
||||
async function updateTaskHandler(req, { params }) {
|
||||
const { id } = await params;
|
||||
try {
|
||||
const { name, max_wait_days, description } = await req.json();
|
||||
|
||||
@@ -40,7 +42,7 @@ async function updateTaskHandler(req, { params }) {
|
||||
SET name = ?, max_wait_days = ?, description = ?
|
||||
WHERE task_id = ? AND is_standard = 1`
|
||||
)
|
||||
.run(name, max_wait_days || 0, description || null, params.id);
|
||||
.run(name, max_wait_days || 0, description || null, id);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return NextResponse.json(
|
||||
@@ -60,10 +62,11 @@ async function updateTaskHandler(req, { params }) {
|
||||
|
||||
// DELETE: Delete a task template
|
||||
async function deleteTaskHandler(req, { params }) {
|
||||
const { id } = await params;
|
||||
try {
|
||||
const result = db
|
||||
.prepare("DELETE FROM tasks WHERE task_id = ? AND is_standard = 1")
|
||||
.run(params.id);
|
||||
.run(id);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return NextResponse.json(
|
||||
|
||||
@@ -16,6 +16,8 @@ import PageContainer from "@/components/ui/PageContainer";
|
||||
import PageHeader from "@/components/ui/PageHeader";
|
||||
import ProjectStatusDropdown from "@/components/ProjectStatusDropdown";
|
||||
import ClientProjectMap from "@/components/ui/ClientProjectMap";
|
||||
import FileUploadBox from "@/components/FileUploadBox";
|
||||
import FileItem from "@/components/FileItem";
|
||||
|
||||
export default function ProjectViewPage() {
|
||||
const params = useParams();
|
||||
@@ -23,6 +25,7 @@ export default function ProjectViewPage() {
|
||||
const [project, setProject] = useState(null);
|
||||
const [notes, setNotes] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [uploadedFiles, setUploadedFiles] = useState([]);
|
||||
|
||||
// Helper function to add a new note to the list
|
||||
const addNote = (newNote) => {
|
||||
@@ -40,6 +43,39 @@ export default function ProjectViewPage() {
|
||||
return note.created_by === session.user.id;
|
||||
};
|
||||
|
||||
// Helper function to handle file upload
|
||||
const handleFileUploaded = (newFile) => {
|
||||
setUploadedFiles(prevFiles => [newFile, ...prevFiles]);
|
||||
};
|
||||
|
||||
// Helper function to handle file deletion
|
||||
const handleFileDelete = async (fileId) => {
|
||||
if (confirm('Czy na pewno chcesz usunąć ten plik?')) {
|
||||
try {
|
||||
const res = await fetch(`/api/files/${fileId}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
if (res.ok) {
|
||||
setUploadedFiles(prevFiles => prevFiles.filter(file => file.file_id !== fileId));
|
||||
} else {
|
||||
alert('Błąd podczas usuwania pliku');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting file:', error);
|
||||
alert('Błąd podczas usuwania pliku');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Helper function to handle file update (edit)
|
||||
const handleFileUpdate = async (updatedFile) => {
|
||||
setUploadedFiles(prevFiles =>
|
||||
prevFiles.map(file =>
|
||||
file.file_id === updatedFile.file_id ? updatedFile : file
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
if (!params.id) return;
|
||||
@@ -56,8 +92,13 @@ export default function ProjectViewPage() {
|
||||
const notesRes = await fetch(`/api/notes?project_id=${params.id}`);
|
||||
const notesData = notesRes.ok ? await notesRes.json() : [];
|
||||
|
||||
// Fetch files data
|
||||
const filesRes = await fetch(`/api/files?entityType=project&entityId=${params.id}`);
|
||||
const filesData = filesRes.ok ? await filesRes.json() : [];
|
||||
|
||||
setProject(projectData);
|
||||
setNotes(notesData);
|
||||
setUploadedFiles(filesData);
|
||||
} catch (error) {
|
||||
console.error('Error fetching data:', error);
|
||||
setProject(null);
|
||||
@@ -168,7 +209,7 @@ export default function ProjectViewPage() {
|
||||
<Link href={`/projects/${params.id}/edit`} className="flex-1">
|
||||
<Button variant="primary" size="sm" className="w-full text-xs">
|
||||
<svg
|
||||
className="w-4 h-4 mr-1"
|
||||
className="w-4 h-4 mr-1"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
@@ -229,7 +270,7 @@ export default function ProjectViewPage() {
|
||||
className="w-4 h-4 mr-2"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
@@ -493,7 +534,7 @@ export default function ProjectViewPage() {
|
||||
<Link href="/projects" className="block">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
size="sm"
|
||||
className="w-full justify-start"
|
||||
>
|
||||
<svg
|
||||
@@ -536,6 +577,31 @@ export default function ProjectViewPage() {
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* File Upload */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h2 className="text-lg font-semibold text-gray-900">
|
||||
Załączniki
|
||||
</h2>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<FileUploadBox projectId={params.id} onFileUploaded={handleFileUploaded} />
|
||||
{uploadedFiles.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-medium text-gray-700">Przesłane pliki:</h3>
|
||||
{uploadedFiles.map((file) => (
|
||||
<FileItem
|
||||
key={file.file_id}
|
||||
file={file}
|
||||
onDelete={handleFileDelete}
|
||||
onUpdate={handleFileUpdate}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
{/* Project Location Map */}
|
||||
|
||||
181
src/components/FileItem.js
Normal file
181
src/components/FileItem.js
Normal file
@@ -0,0 +1,181 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Button from "@/components/ui/Button";
|
||||
|
||||
export default function FileItem({ file, onDelete, onUpdate }) {
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [editFilename, setEditFilename] = useState(file.original_filename);
|
||||
const [editDescription, setEditDescription] = useState(file.description || "");
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/files/${file.file_id}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
original_filename: editFilename,
|
||||
description: editDescription,
|
||||
}),
|
||||
});
|
||||
if (res.ok) {
|
||||
const updatedFile = await res.json();
|
||||
onUpdate(updatedFile);
|
||||
setIsEditing(false);
|
||||
} else {
|
||||
alert('Błąd podczas aktualizacji pliku');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating file:', error);
|
||||
alert('Błąd podczas aktualizacji pliku');
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setEditFilename(file.original_filename);
|
||||
setEditDescription(file.description || "");
|
||||
setIsEditing(false);
|
||||
};
|
||||
|
||||
const formatFileSize = (bytes) => {
|
||||
if (!bytes) return '';
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
const k = 1024;
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
};
|
||||
|
||||
const getFileIcon = (filename) => {
|
||||
const ext = filename.split('.').pop().toLowerCase();
|
||||
if (['jpg', 'jpeg', 'png', 'gif'].includes(ext)) {
|
||||
return (
|
||||
<svg className="w-4 h-4 text-blue-500" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clipRule="evenodd" />
|
||||
</svg>
|
||||
);
|
||||
} else if (ext === 'pdf') {
|
||||
return (
|
||||
<svg className="w-4 h-4 text-red-500" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clipRule="evenodd" />
|
||||
</svg>
|
||||
);
|
||||
} else if (['doc', 'docx'].includes(ext)) {
|
||||
return (
|
||||
<svg className="w-4 h-4 text-blue-600" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clipRule="evenodd" />
|
||||
</svg>
|
||||
);
|
||||
} else if (['xls', 'xlsx'].includes(ext)) {
|
||||
return (
|
||||
<svg className="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clipRule="evenodd" />
|
||||
</svg>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<svg className="w-4 h-4 text-gray-500" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clipRule="evenodd" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
if (isEditing) {
|
||||
return (
|
||||
<div className="p-3 bg-gray-50 rounded-lg border">
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-gray-700 mb-1">
|
||||
Nazwa pliku
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={editFilename}
|
||||
onChange={(e) => setEditFilename(e.target.value)}
|
||||
className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-gray-700 mb-1">
|
||||
Opis (opcjonalny)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={editDescription}
|
||||
onChange={(e) => setEditDescription(e.target.value)}
|
||||
className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
|
||||
placeholder="Dodaj opis pliku..."
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={handleSave}>
|
||||
Zapisz
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={handleCancel}>
|
||||
Anuluj
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors group">
|
||||
<div className="flex items-center flex-1 min-w-0">
|
||||
<div className="flex-shrink-0 mr-3">
|
||||
{getFileIcon(file.original_filename)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-medium text-gray-900 truncate">
|
||||
{file.original_filename}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 flex items-center gap-2">
|
||||
<span>{formatFileSize(file.file_size)}</span>
|
||||
<span>•</span>
|
||||
<span>{new Date(file.upload_date).toLocaleDateString('pl-PL')}</span>
|
||||
</div>
|
||||
{file.description && (
|
||||
<div className="text-xs text-gray-600 mt-1 truncate">
|
||||
{file.description}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 ml-3">
|
||||
<a
|
||||
href={`/api/files/${file.file_id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:text-blue-800 p-1 rounded"
|
||||
title="Pobierz"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
||||
</svg>
|
||||
</a>
|
||||
<button
|
||||
onClick={() => setIsEditing(true)}
|
||||
className="text-gray-600 hover:text-gray-800 p-1 rounded opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
title="Edytuj"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onDelete(file.file_id)}
|
||||
className="text-red-600 hover:text-red-800 p-1 rounded opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
title="Usuń"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
137
src/components/FileUploadBox.js
Normal file
137
src/components/FileUploadBox.js
Normal file
@@ -0,0 +1,137 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef, useCallback } from "react";
|
||||
import Button from "@/components/ui/Button";
|
||||
|
||||
export default function FileUploadBox({ projectId, onFileUploaded }) {
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const fileInputRef = useRef(null);
|
||||
|
||||
const acceptedTypes = ".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.gif,.txt,.dwg,.zip";
|
||||
|
||||
const uploadFiles = async (files) => {
|
||||
const validFiles = Array.from(files).filter(file => {
|
||||
const isValidType = acceptedTypes.split(',').some(type =>
|
||||
file.name.toLowerCase().endsWith(type.replace('*', ''))
|
||||
);
|
||||
const isValidSize = file.size <= 10 * 1024 * 1024; // 10MB limit
|
||||
return isValidType && isValidSize;
|
||||
});
|
||||
|
||||
if (validFiles.length === 0) {
|
||||
alert('No valid files selected (invalid type or size > 10MB)');
|
||||
return;
|
||||
}
|
||||
|
||||
if (validFiles.length !== files.length) {
|
||||
alert('Some files were skipped due to invalid type or size (max 10MB)');
|
||||
}
|
||||
|
||||
setUploading(true);
|
||||
const uploadPromises = validFiles.map(async (file) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append("entityType", "project");
|
||||
formData.append("entityId", projectId.toString());
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/files", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const uploadedFile = await response.json();
|
||||
onFileUploaded?.(uploadedFile);
|
||||
return { success: true };
|
||||
} else {
|
||||
const error = await response.json();
|
||||
return { success: false, error: error.error || "Upload failed" };
|
||||
}
|
||||
} catch (error) {
|
||||
return { success: false, error: "Network error" };
|
||||
}
|
||||
});
|
||||
|
||||
const results = await Promise.all(uploadPromises);
|
||||
const failed = results.filter(r => !r.success);
|
||||
|
||||
if (failed.length > 0) {
|
||||
alert(`Failed to upload ${failed.length} file(s)`);
|
||||
}
|
||||
|
||||
setUploading(false);
|
||||
};
|
||||
|
||||
const handleInputChange = (e) => {
|
||||
if (e.target.files.length > 0) {
|
||||
uploadFiles(e.target.files);
|
||||
}
|
||||
e.target.value = ''; // Reset input
|
||||
};
|
||||
|
||||
const handleDrop = useCallback((e) => {
|
||||
e.preventDefault();
|
||||
setDragOver(false);
|
||||
if (e.dataTransfer.files.length > 0) {
|
||||
uploadFiles(e.dataTransfer.files);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleDragOver = useCallback((e) => {
|
||||
e.preventDefault();
|
||||
setDragOver(true);
|
||||
}, []);
|
||||
|
||||
const handleDragLeave = useCallback((e) => {
|
||||
e.preventDefault();
|
||||
setDragOver(false);
|
||||
}, []);
|
||||
|
||||
const handleClick = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center hover:border-gray-400 transition-colors cursor-pointer">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleInputChange}
|
||||
accept={acceptedTypes}
|
||||
disabled={uploading}
|
||||
/>
|
||||
|
||||
{uploading ? (
|
||||
<div className="flex flex-col items-center">
|
||||
<svg className="animate-spin h-6 w-6 text-blue-600 mb-2" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
|
||||
</svg>
|
||||
<span className="text-xs text-gray-600">Przesyłanie plików...</span>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={`flex flex-col items-center ${dragOver ? 'scale-105' : ''} transition-transform`}
|
||||
onDrop={handleDrop}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onClick={handleClick}
|
||||
>
|
||||
<svg className="w-8 h-8 text-gray-400 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
|
||||
</svg>
|
||||
<span className="text-sm font-medium text-gray-900 mb-1">
|
||||
{dragOver ? 'Upuść pliki tutaj' : 'Przeciągnij pliki lub kliknij'}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
PDF, DOC, XLS, obrazki, DWG, ZIP
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user