feat: Implement file upload and management system with database integration
This commit is contained in:
5
init-db-temp.mjs
Normal file
5
init-db-temp.mjs
Normal file
@@ -0,0 +1,5 @@
|
||||
import initializeDatabase from './src/lib/init-db.js';
|
||||
|
||||
console.log('Initializing database...');
|
||||
initializeDatabase();
|
||||
console.log('Database initialized successfully!');
|
||||
60
migrate-to-username.js
Normal file
60
migrate-to-username.js
Normal file
@@ -0,0 +1,60 @@
|
||||
import Database from "better-sqlite3";
|
||||
|
||||
const db = new Database("./data/database.sqlite");
|
||||
|
||||
console.log("🔄 Migrating database to username-based authentication...\n");
|
||||
|
||||
try {
|
||||
// Check current table structure
|
||||
const tableInfo = db.prepare("PRAGMA table_info(users)").all();
|
||||
console.log("Current users table columns:");
|
||||
tableInfo.forEach(col => console.log(` - ${col.name}: ${col.type}`));
|
||||
|
||||
const hasUsername = tableInfo.some(col => col.name === 'username');
|
||||
const hasEmail = tableInfo.some(col => col.name === 'email');
|
||||
|
||||
if (hasUsername) {
|
||||
console.log("✅ Username column already exists!");
|
||||
} else if (hasEmail) {
|
||||
console.log("\n📝 Adding username column...");
|
||||
|
||||
// Add username column
|
||||
db.exec(`ALTER TABLE users ADD COLUMN username TEXT;`);
|
||||
console.log("✅ Username column added");
|
||||
|
||||
// Copy email data to username for existing users
|
||||
console.log("📋 Migrating existing email data to username...");
|
||||
const result = db.exec(`UPDATE users SET username = email WHERE username IS NULL;`);
|
||||
console.log("✅ Data migrated");
|
||||
|
||||
// Create unique index on username
|
||||
console.log("🔍 Creating unique index on username...");
|
||||
try {
|
||||
db.exec(`CREATE UNIQUE INDEX idx_users_username_unique ON users(username);`);
|
||||
console.log("✅ Unique index created");
|
||||
} catch (e) {
|
||||
console.log("ℹ️ Index already exists or couldn't be created:", e.message);
|
||||
}
|
||||
|
||||
// Verify migration
|
||||
console.log("\n🔍 Verifying migration...");
|
||||
const users = db.prepare("SELECT id, name, username, email FROM users LIMIT 3").all();
|
||||
console.log("Sample users after migration:");
|
||||
users.forEach(user => {
|
||||
console.log(` - ${user.name}: username="${user.username}", email="${user.email || 'NULL'}"`);
|
||||
});
|
||||
|
||||
console.log("\n✅ Migration completed successfully!");
|
||||
console.log("ℹ️ You can now log in using usernames instead of emails");
|
||||
|
||||
} else {
|
||||
console.log("❌ Neither username nor email column found. Database may be corrupted.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error("❌ Migration failed:", error.message);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
79
src/app/api/files/[fileId]/route.js
Normal file
79
src/app/api/files/[fileId]/route.js
Normal file
@@ -0,0 +1,79 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { unlink } from "fs/promises";
|
||||
import path from "path";
|
||||
import db from "@/lib/db";
|
||||
|
||||
export async function DELETE(request, { params }) {
|
||||
try {
|
||||
const fileId = params.fileId;
|
||||
|
||||
// Get file info from database
|
||||
const file = db.prepare(`
|
||||
SELECT * FROM file_attachments WHERE file_id = ?
|
||||
`).get(parseInt(fileId));
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json(
|
||||
{ error: "File not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Delete physical file
|
||||
try {
|
||||
const fullPath = path.join(process.cwd(), "public", file.file_path);
|
||||
await unlink(fullPath);
|
||||
} catch (fileError) {
|
||||
console.warn("Could not delete physical file:", fileError.message);
|
||||
// Continue with database deletion even if file doesn't exist
|
||||
}
|
||||
|
||||
// Delete from database
|
||||
const result = db.prepare(`
|
||||
DELETE FROM file_attachments WHERE file_id = ?
|
||||
`).run(parseInt(fileId));
|
||||
|
||||
if (result.changes === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "File not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error deleting file:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to delete file" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request, { params }) {
|
||||
try {
|
||||
const fileId = params.fileId;
|
||||
|
||||
// Get file info from database
|
||||
const file = db.prepare(`
|
||||
SELECT * FROM file_attachments WHERE file_id = ?
|
||||
`).get(parseInt(fileId));
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json(
|
||||
{ error: "File not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(file);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error fetching file:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch file" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
162
src/app/api/files/route.js
Normal file
162
src/app/api/files/route.js
Normal file
@@ -0,0 +1,162 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { writeFile, mkdir } from "fs/promises";
|
||||
import { existsSync } from "fs";
|
||||
import path from "path";
|
||||
import db from "@/lib/db";
|
||||
import { auditLog } from "@/lib/middleware/auditLog";
|
||||
|
||||
const UPLOAD_DIR = path.join(process.cwd(), "public", "uploads");
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
|
||||
const ALLOWED_TYPES = [
|
||||
"application/pdf",
|
||||
"application/msword",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"application/vnd.ms-excel",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/gif",
|
||||
"text/plain"
|
||||
];
|
||||
|
||||
export async function POST(request) {
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
const file = formData.get("file");
|
||||
const entityType = formData.get("entityType");
|
||||
const entityId = formData.get("entityId");
|
||||
const description = formData.get("description") || "";
|
||||
|
||||
if (!file || !entityType || !entityId) {
|
||||
return NextResponse.json(
|
||||
{ error: "File, entityType, and entityId are required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate entity type
|
||||
if (!["contract", "project", "task"].includes(entityType)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid entity type" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate file
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
return NextResponse.json(
|
||||
{ error: "File size too large (max 10MB)" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!ALLOWED_TYPES.includes(file.type)) {
|
||||
return NextResponse.json(
|
||||
{ error: "File type not allowed" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Create upload directory structure
|
||||
const entityDir = path.join(UPLOAD_DIR, entityType + "s", entityId);
|
||||
if (!existsSync(entityDir)) {
|
||||
await mkdir(entityDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Generate unique filename
|
||||
const timestamp = Date.now();
|
||||
const sanitizedOriginalName = file.name.replace(/[^a-zA-Z0-9.-]/g, "_");
|
||||
const storedFilename = `${timestamp}_${sanitizedOriginalName}`;
|
||||
const filePath = path.join(entityDir, storedFilename);
|
||||
const relativePath = `/uploads/${entityType}s/${entityId}/${storedFilename}`;
|
||||
|
||||
// Save file
|
||||
const bytes = await file.arrayBuffer();
|
||||
const buffer = Buffer.from(bytes);
|
||||
await writeFile(filePath, buffer);
|
||||
|
||||
// Save to database
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO file_attachments (
|
||||
entity_type, entity_id, original_filename, stored_filename,
|
||||
file_path, file_size, mime_type, description, uploaded_by
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
const result = stmt.run(
|
||||
entityType,
|
||||
parseInt(entityId),
|
||||
file.name,
|
||||
storedFilename,
|
||||
relativePath,
|
||||
file.size,
|
||||
file.type,
|
||||
description,
|
||||
null // TODO: Get from session when auth is implemented
|
||||
);
|
||||
|
||||
const newFile = {
|
||||
file_id: result.lastInsertRowid,
|
||||
entity_type: entityType,
|
||||
entity_id: parseInt(entityId),
|
||||
original_filename: file.name,
|
||||
stored_filename: storedFilename,
|
||||
file_path: relativePath,
|
||||
file_size: file.size,
|
||||
mime_type: file.type,
|
||||
description: description,
|
||||
upload_date: new Date().toISOString()
|
||||
};
|
||||
|
||||
return NextResponse.json(newFile, { status: 201 });
|
||||
|
||||
} catch (error) {
|
||||
console.error("File upload error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to upload file" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const entityType = searchParams.get("entityType");
|
||||
const entityId = searchParams.get("entityId");
|
||||
|
||||
if (!entityType || !entityId) {
|
||||
return NextResponse.json(
|
||||
{ error: "entityType and entityId are required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const files = db.prepare(`
|
||||
SELECT
|
||||
file_id,
|
||||
entity_type,
|
||||
entity_id,
|
||||
original_filename,
|
||||
stored_filename,
|
||||
file_path,
|
||||
file_size,
|
||||
mime_type,
|
||||
description,
|
||||
upload_date,
|
||||
uploaded_by
|
||||
FROM file_attachments
|
||||
WHERE entity_type = ? AND entity_id = ?
|
||||
ORDER BY upload_date DESC
|
||||
`).all(entityType, parseInt(entityId));
|
||||
|
||||
return NextResponse.json(files);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error fetching files:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch files" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import PageContainer from "@/components/ui/PageContainer";
|
||||
import PageHeader from "@/components/ui/PageHeader";
|
||||
import { LoadingState } from "@/components/ui/States";
|
||||
import { formatDate } from "@/lib/utils";
|
||||
import FileUploadModal from "@/components/FileUploadModal";
|
||||
import FileAttachmentsList from "@/components/FileAttachmentsList";
|
||||
|
||||
export default function ContractDetailsPage() {
|
||||
const params = useParams();
|
||||
@@ -17,6 +19,8 @@ export default function ContractDetailsPage() {
|
||||
const [contract, setContract] = useState(null);
|
||||
const [projects, setProjects] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showUploadModal, setShowUploadModal] = useState(false);
|
||||
const [attachments, setAttachments] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchContractDetails() {
|
||||
@@ -52,6 +56,14 @@ export default function ContractDetailsPage() {
|
||||
fetchContractDetails();
|
||||
}
|
||||
}, [contractId]);
|
||||
const handleFileUploaded = (newFile) => {
|
||||
setAttachments(prev => [newFile, ...prev]);
|
||||
};
|
||||
|
||||
const handleFilesChange = (files) => {
|
||||
setAttachments(files);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<PageContainer>
|
||||
@@ -245,6 +257,44 @@ export default function ContractDetailsPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Contract Documents */}
|
||||
<Card className="mb-8">
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-center">
|
||||
<h2 className="text-xl font-semibold text-gray-900">
|
||||
Contract Documents ({attachments.length})
|
||||
</h2>
|
||||
<Button
|
||||
variant="primary"
|
||||
size="sm"
|
||||
onClick={() => setShowUploadModal(true)}
|
||||
>
|
||||
<svg
|
||||
className="w-4 h-4 mr-2"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
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>
|
||||
Upload Document
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<FileAttachmentsList
|
||||
entityType="contract"
|
||||
entityId={contractId}
|
||||
onFilesChange={handleFilesChange}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Associated Projects */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -386,6 +436,15 @@ export default function ContractDetailsPage() {
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* File Upload Modal */}
|
||||
<FileUploadModal
|
||||
isOpen={showUploadModal}
|
||||
onClose={() => setShowUploadModal(false)}
|
||||
entityType="contract"
|
||||
entityId={contractId}
|
||||
onFileUploaded={handleFileUploaded}
|
||||
/>
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
177
src/components/FileAttachmentsList.js
Normal file
177
src/components/FileAttachmentsList.js
Normal file
@@ -0,0 +1,177 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Button from "@/components/ui/Button";
|
||||
import { formatDate } from "@/lib/utils";
|
||||
|
||||
export default function FileAttachmentsList({ entityType, entityId, onFilesChange }) {
|
||||
const [files, setFiles] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const fetchFiles = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/files?entityType=${entityType}&entityId=${entityId}`);
|
||||
if (response.ok) {
|
||||
const filesData = await response.json();
|
||||
setFiles(filesData);
|
||||
if (onFilesChange) {
|
||||
onFilesChange(filesData);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching files:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchFiles();
|
||||
}, [entityType, entityId]);
|
||||
|
||||
const handleDelete = async (fileId) => {
|
||||
if (!confirm("Are you sure you want to delete this file?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/files/${fileId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
setFiles(files.filter(file => file.file_id !== fileId));
|
||||
if (onFilesChange) {
|
||||
onFilesChange(files.filter(file => file.file_id !== fileId));
|
||||
}
|
||||
} else {
|
||||
alert("Failed to delete file");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error deleting file:", error);
|
||||
alert("Failed to delete file");
|
||||
}
|
||||
};
|
||||
|
||||
const formatFileSize = (bytes) => {
|
||||
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 = (mimeType) => {
|
||||
if (mimeType.startsWith('image/')) {
|
||||
return (
|
||||
<svg className="w-5 h-5 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 (mimeType === 'application/pdf') {
|
||||
return (
|
||||
<svg className="w-5 h-5 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 (mimeType.includes('word') || mimeType.includes('document')) {
|
||||
return (
|
||||
<svg className="w-5 h-5 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 (mimeType.includes('excel') || mimeType.includes('sheet')) {
|
||||
return (
|
||||
<svg className="w-5 h-5 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-5 h-5 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 (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<svg className="animate-spin h-6 w-6 text-gray-400" 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="ml-2 text-gray-500">Loading files...</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (files.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-8">
|
||||
<svg className="w-12 h-12 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 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>
|
||||
<p className="text-gray-500">No documents uploaded yet</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{files.map((file) => (
|
||||
<div
|
||||
key={file.file_id}
|
||||
className="flex items-center justify-between p-3 border border-gray-200 rounded-lg hover:bg-gray-50"
|
||||
>
|
||||
<div className="flex items-center flex-1 min-w-0">
|
||||
<div className="flex-shrink-0 mr-3">
|
||||
{getFileIcon(file.mime_type)}
|
||||
</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>{formatDate(file.upload_date, { includeTime: true })}</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-2 ml-3">
|
||||
<a
|
||||
href={file.file_path}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
<Button variant="outline" size="sm">
|
||||
<svg className="w-4 h-4 mr-1" 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>
|
||||
Download
|
||||
</Button>
|
||||
</a>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleDelete(file.file_id)}
|
||||
className="text-red-600 hover:text-red-800 hover:border-red-300"
|
||||
>
|
||||
<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>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
186
src/components/FileUploadModal.js
Normal file
186
src/components/FileUploadModal.js
Normal file
@@ -0,0 +1,186 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
import Button from "@/components/ui/Button";
|
||||
|
||||
export default function FileUploadModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
entityType,
|
||||
entityId,
|
||||
onFileUploaded
|
||||
}) {
|
||||
const [dragActive, setDragActive] = useState(false);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [description, setDescription] = useState("");
|
||||
const fileInputRef = useRef(null);
|
||||
|
||||
const handleDrag = (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (e.type === "dragenter" || e.type === "dragover") {
|
||||
setDragActive(true);
|
||||
} else if (e.type === "dragleave") {
|
||||
setDragActive(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDrop = (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setDragActive(false);
|
||||
|
||||
if (e.dataTransfer.files && e.dataTransfer.files[0]) {
|
||||
handleFiles(e.dataTransfer.files);
|
||||
}
|
||||
};
|
||||
|
||||
const handleChange = (e) => {
|
||||
e.preventDefault();
|
||||
if (e.target.files && e.target.files[0]) {
|
||||
handleFiles(e.target.files);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFiles = async (files) => {
|
||||
const file = files[0];
|
||||
if (!file) return;
|
||||
|
||||
setUploading(true);
|
||||
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append("entityType", entityType);
|
||||
formData.append("entityId", entityId.toString());
|
||||
formData.append("description", description);
|
||||
|
||||
const response = await fetch("/api/files", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const uploadedFile = await response.json();
|
||||
onFileUploaded(uploadedFile);
|
||||
setDescription("");
|
||||
onClose();
|
||||
} else {
|
||||
const error = await response.json();
|
||||
alert(error.error || "Failed to upload file");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Upload error:", error);
|
||||
alert("Failed to upload file");
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onButtonClick = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white rounded-lg p-6 w-full max-w-md mx-4">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h3 className="text-lg font-semibold text-gray-900">
|
||||
Upload Document
|
||||
</h3>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600"
|
||||
disabled={uploading}
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Description Input */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Description (optional)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Brief description of the document..."
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
|
||||
disabled={uploading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* File Drop Zone */}
|
||||
<div
|
||||
className={`relative border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
|
||||
dragActive
|
||||
? "border-blue-400 bg-blue-50"
|
||||
: "border-gray-300 hover:border-gray-400"
|
||||
} ${uploading ? "opacity-50 pointer-events-none" : ""}`}
|
||||
onDragEnter={handleDrag}
|
||||
onDragLeave={handleDrag}
|
||||
onDragOver={handleDrag}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
onChange={handleChange}
|
||||
accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.gif,.txt"
|
||||
disabled={uploading}
|
||||
/>
|
||||
|
||||
{uploading ? (
|
||||
<div className="flex flex-col items-center">
|
||||
<svg className="animate-spin h-8 w-8 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-sm text-gray-600">Uploading...</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center">
|
||||
<svg className="w-12 h-12 text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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-2">
|
||||
Drop files here or click to browse
|
||||
</span>
|
||||
<span className="text-xs text-gray-500 mb-4">
|
||||
PDF, DOC, XLS, Images up to 10MB
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onButtonClick}
|
||||
disabled={uploading}
|
||||
>
|
||||
Choose File
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 mt-6">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onClose}
|
||||
disabled={uploading}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -341,4 +341,26 @@ export default function initializeDatabase() {
|
||||
} catch (e) {
|
||||
console.warn("Migration warning:", e.message);
|
||||
}
|
||||
|
||||
// Generic file attachments table
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS file_attachments (
|
||||
file_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
entity_type TEXT NOT NULL CHECK(entity_type IN ('contract', 'project', 'task')),
|
||||
entity_id INTEGER NOT NULL,
|
||||
original_filename TEXT NOT NULL,
|
||||
stored_filename TEXT NOT NULL,
|
||||
file_path TEXT NOT NULL,
|
||||
file_size INTEGER,
|
||||
mime_type TEXT,
|
||||
description TEXT,
|
||||
uploaded_by TEXT,
|
||||
upload_date TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (uploaded_by) REFERENCES users(id)
|
||||
);
|
||||
|
||||
-- Create indexes for file attachments
|
||||
CREATE INDEX IF NOT EXISTS idx_file_attachments_entity ON file_attachments(entity_type, entity_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_file_attachments_uploaded_by ON file_attachments(uploaded_by);
|
||||
`);
|
||||
}
|
||||
|
||||
28
update-admin-username.js
Normal file
28
update-admin-username.js
Normal file
@@ -0,0 +1,28 @@
|
||||
import Database from "better-sqlite3";
|
||||
|
||||
const db = new Database("./data/database.sqlite");
|
||||
|
||||
console.log("🔄 Updating admin username...");
|
||||
|
||||
try {
|
||||
// Update admin username from email to simple "admin"
|
||||
const result = db.prepare('UPDATE users SET username = ? WHERE username = ?').run('admin', 'admin@localhost.com');
|
||||
|
||||
if (result.changes > 0) {
|
||||
console.log('✅ Admin username updated to "admin"');
|
||||
} else {
|
||||
console.log('ℹ️ No admin user found with email "admin@localhost.com"');
|
||||
}
|
||||
|
||||
// Show current users
|
||||
const users = db.prepare("SELECT name, username, role FROM users").all();
|
||||
console.log("\nCurrent users:");
|
||||
users.forEach(user => {
|
||||
console.log(` - ${user.name} (${user.role}): username="${user.username}"`);
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error("❌ Error:", error.message);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
Reference in New Issue
Block a user