Files
EduCatWeb/views/dashboard.ejs

672 lines
30 KiB
Plaintext

<%- include('partials/header') %>
<div class="container py-5">
<div class="row">
<div class="col-12">
<div class="d-flex justify-content-between align-items-center mb-4">
<h2><i class="fas fa-tachometer-alt me-2"></i>Your Dashboard</h2>
<a href="/upload" class="btn btn-primary">
<i class="fas fa-plus me-2"></i>Upload New Notes
</a>
</div>
<% if (files.length === 0) { %>
<div class="text-center py-5">
<i class="fas fa-folder-open fa-4x text-muted mb-4"></i>
<h4>No files uploaded yet</h4>
<p class="text-muted">Upload your first set of notes to get started with AI-powered revision.</p>
<a href="/upload" class="btn btn-primary btn-lg">
<i class="fas fa-upload me-2"></i>Upload Notes
</a>
</div>
<% } else { %>
<div class="row">
<% files.forEach(function(file, index) { %>
<div class="col-md-6 col-lg-4 mb-4">
<div class="card border-0 shadow-sm h-100">
<div class="card-body">
<div class="d-flex align-items-center mb-3">
<div class="file-icon bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 50px; height: 50px;">
<i class="fas fa-file-alt"></i>
</div>
<div class="flex-grow-1">
<h6 class="mb-1"><%= file.originalName %></h6>
<small class="text-muted"><%= Math.round(file.size / 1024) %> KB</small>
</div>
<div class="text-end">
<% if (file.status === 'processing') { %>
<span class="badge bg-warning">
<i class="fas fa-spinner fa-spin me-1"></i>Processing
</span>
<% } else if (file.status === 'processed') { %>
<span class="badge bg-success">
<i class="fas fa-check me-1"></i>Processed
</span>
<% } else if (file.status === 'failed') { %>
<span class="badge bg-danger">
<i class="fas fa-times me-1"></i>Failed
</span>
<% } else { %>
<span class="badge bg-secondary">
<i class="fas fa-clock me-1"></i>Uploaded
</span>
<% } %>
</div>
</div>
<div class="mb-3">
<small class="text-muted">
<i class="fas fa-calendar me-1"></i>
Uploaded: <%= new Date(file.uploadDate).toLocaleDateString() %>
</small>
<% if (file.processingResult) { %>
<br><small class="text-muted">
<i class="fas fa-puzzle-piece me-1"></i>
Chunks: <%= file.processingResult.successfulChunks %>/<%= file.processingResult.totalChunks %>
</small>
<% } %>
</div>
<div class="d-grid gap-2">
<% if (file.status === 'processed') { %>
<a href="/revise/<%= file.id %>" class="btn btn-primary btn-sm">
<i class="fas fa-brain me-2"></i>Revise with AI
</a>
<% } else if (file.status === 'processing') { %>
<button class="btn btn-secondary btn-sm" disabled>
<i class="fas fa-spinner fa-spin me-2"></i>Processing...
</button>
<% } else if (file.status === 'failed') { %>
<button class="btn btn-warning btn-sm" onclick="retryProcessing('<%= file.id %>')">
<i class="fas fa-redo me-2"></i>Retry Processing
</button>
<% } else { %>
<button class="btn btn-info btn-sm" onclick="checkProcessingStatus('<%= file.id %>')">
<i class="fas fa-sync me-2"></i>Check Status
</button>
<% } %>
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary btn-sm" onclick="previewFile('<%= file.id %>')">
<i class="fas fa-eye"></i> Preview
</button>
<button type="button" class="btn btn-outline-info btn-sm" onclick="viewProcessingDetails('<%= file.id %>')">
<i class="fas fa-info-circle"></i> Details
</button>
<button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteFile('<%= file.id %>')">
<i class="fas fa-trash"></i> Delete
</button>
</div>
</div>
</div>
</div>
</div>
<% }); %>
</div>
<% } %>
</div>
</div>
</div>
<!-- Preview Modal -->
<div class="modal fade" id="previewModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">File Preview</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div id="preview-content">
<div class="text-center">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2">Loading preview...</p>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Processing Details Modal -->
<div class="modal fade" id="processingDetailsModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Processing Details</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div id="processing-details-content">
<div class="text-center">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2">Loading processing details...</p>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
function previewFile(fileId) {
const modal = new bootstrap.Modal(document.getElementById('previewModal'));
const previewContent = document.getElementById('preview-content');
previewContent.innerHTML = `
<div class="text-center">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2">Loading preview...</p>
</div>
`;
modal.show();
// Fetch file content for preview
fetch(`/api/files/${fileId}/preview`)
.then(response => response.json())
.then(result => {
if (result.success) {
const file = result.file;
let content = '';
// Check file type and format content accordingly
const fileExtension = file.originalName.split('.').pop().toLowerCase();
if (['txt', 'md', 'json', 'js', 'html', 'css', 'py', 'java', 'cpp', 'c'].includes(fileExtension)) {
// Text-based files - show with syntax highlighting
content = `
<div class="mb-3">
<h6><i class="fas fa-file-alt me-2"></i>${file.originalName}</h6>
<small class="text-muted">
Size: ${Math.round(file.size / 1024)} KB |
Uploaded: ${new Date(file.uploadDate).toLocaleDateString()}
</small>
</div>
<div class="border rounded p-3" style="background-color: #f8f9fa; max-height: 400px; overflow-y: auto;">
<pre style="margin: 0; white-space: pre-wrap; word-wrap: break-word;"><code>${escapeHtml(file.content)}</code></pre>
</div>
`;
} else if (['pdf', 'doc', 'docx'].includes(fileExtension)) {
// Document files - show basic info and content preview
content = `
<div class="mb-3">
<h6><i class="fas fa-file-pdf me-2"></i>${file.originalName}</h6>
<small class="text-muted">
Size: ${Math.round(file.size / 1024)} KB |
Uploaded: ${new Date(file.uploadDate).toLocaleDateString()}
</small>
</div>
<div class="alert alert-info">
<i class="fas fa-info-circle me-2"></i>
Document preview: First few lines of extracted text
</div>
<div class="border rounded p-3" style="background-color: #f8f9fa; max-height: 400px; overflow-y: auto;">
<pre style="margin: 0; white-space: pre-wrap; word-wrap: break-word;">${escapeHtml(file.content.substring(0, 1000))}${file.content.length > 1000 ? '...' : ''}</pre>
</div>
`;
} else {
// Other files - show basic info
content = `
<div class="mb-3">
<h6><i class="fas fa-file me-2"></i>${file.originalName}</h6>
<small class="text-muted">
Size: ${Math.round(file.size / 1024)} KB |
Uploaded: ${new Date(file.uploadDate).toLocaleDateString()}
</small>
</div>
<div class="alert alert-warning">
<i class="fas fa-exclamation-triangle me-2"></i>
Preview not available for this file type. File content is available for AI processing.
</div>
`;
}
previewContent.innerHTML = content;
} else {
previewContent.innerHTML = `
<div class="alert alert-danger">
<i class="fas fa-exclamation-circle me-2"></i>
Error loading preview: ${result.error || 'Unknown error'}
</div>
`;
}
})
.catch(error => {
previewContent.innerHTML = `
<div class="alert alert-danger">
<i class="fas fa-exclamation-circle me-2"></i>
Error loading preview: ${error.message}
</div>
`;
});
}
// Helper function to escape HTML
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function deleteFile(fileId) {
if (confirm('Are you sure you want to delete this file? This action cannot be undone.')) {
// Show loading state
const deleteBtn = document.querySelector(`button[onclick="deleteFile('${fileId}')"]`);
const originalText = deleteBtn.innerHTML;
deleteBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Deleting...';
deleteBtn.disabled = true;
fetch(`/api/files/${fileId}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(result => {
if (result.success) {
// Show success message
alert('File deleted successfully!');
location.reload();
} else {
alert('Error deleting file: ' + (result.error || 'Unknown error'));
deleteBtn.innerHTML = originalText;
deleteBtn.disabled = false;
}
})
.catch(error => {
console.error('Delete error:', error);
alert('Error deleting file: ' + error.message);
deleteBtn.innerHTML = originalText;
deleteBtn.disabled = false;
});
}
}
// Check processing status
async function checkProcessingStatus(fileId) {
try {
const response = await fetch(`/api/files/${fileId}/status`);
const result = await response.json();
if (result.success) {
// Show status update
const statusInfo = result.file;
let message = `Status: ${statusInfo.status}`;
if (statusInfo.processingResult) {
message += `\nChunks processed: ${statusInfo.processingResult.successfulChunks}/${statusInfo.processingResult.totalChunks}`;
if (statusInfo.processingResult.processedAt) {
message += `\nProcessed at: ${new Date(statusInfo.processingResult.processedAt).toLocaleString()}`;
}
}
if (statusInfo.processingError) {
message += `\nError: ${statusInfo.processingError}`;
}
alert(message);
// Reload page if status changed
if (statusInfo.status !== 'processing') {
location.reload();
}
} else {
alert('Error checking status: ' + result.error);
}
} catch (error) {
console.error('Error checking processing status:', error);
alert('Error checking processing status: ' + error.message);
}
}
// Retry processing
async function retryProcessing(fileId) {
if (confirm('Are you sure you want to retry processing this file?')) {
try {
const response = await fetch(`/api/files/${fileId}/retry`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
});
const result = await response.json();
if (result.success) {
alert('Processing retry initiated. Please check back in a few moments.');
location.reload();
} else {
alert('Error retrying processing: ' + result.error);
}
} catch (error) {
console.error('Error retrying processing:', error);
alert('Error retrying processing: ' + error.message);
}
}
}
// View processing details
async function viewProcessingDetails(fileId) {
try {
const modal = new bootstrap.Modal(document.getElementById('processingDetailsModal'));
const detailsContent = document.getElementById('processing-details-content');
detailsContent.innerHTML = `
<div class="text-center">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2">Loading processing details...</p>
</div>
`;
modal.show();
const response = await fetch(`/api/files/${fileId}/status`);
const result = await response.json();
if (result.success) {
const file = result.file;
let html = `
<div class="mb-3">
<h6><i class="fas fa-file-alt me-2"></i>${escapeHtml(file.originalName)}</h6>
<small class="text-muted">Uploaded: ${new Date(file.uploadDate).toLocaleString()}</small>
</div>
<div class="row mb-3">
<div class="col-md-6">
<strong>Status:</strong>
<span class="ms-2 badge ${file.status === 'processed' ? 'bg-success' : file.status === 'processing' ? 'bg-warning' : file.status === 'failed' ? 'bg-danger' : 'bg-secondary'}">
${file.status}
</span>
</div>
</div>
`;
if (file.processingResult) {
html += `
<div class="card mb-3">
<div class="card-header">
<h6 class="mb-0">Processing Results</h6>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-4">
<strong>Total Chunks:</strong><br>
<span class="badge bg-info">${file.processingResult.totalChunks}</span>
</div>
<div class="col-md-4">
<strong>Successful:</strong><br>
<span class="badge bg-success">${file.processingResult.successfulChunks}</span>
</div>
<div class="col-md-4">
<strong>Failed:</strong><br>
<span class="badge bg-danger">${file.processingResult.failedChunks}</span>
</div>
</div>
${file.processingResult.processedAt ? `
<div class="mt-3">
<strong>Processed At:</strong><br>
<small class="text-muted">${new Date(file.processingResult.processedAt).toLocaleString()}</small>
</div>
` : ''}
${file.processingResult.documentHash ? `
<div class="mt-3">
<strong>Document Hash:</strong><br>
<small class="text-muted font-monospace">${file.processingResult.documentHash}</small>
</div>
` : ''}
${file.processingResult.contentLength ? `
<div class="mt-3">
<strong>Content Length:</strong><br>
<small class="text-muted">${file.processingResult.contentLength.toLocaleString()} characters</small>
</div>
` : ''}
</div>
</div>
`;
}
if (file.processingError) {
html += `
<div class="alert alert-danger">
<h6><i class="fas fa-exclamation-triangle me-2"></i>Processing Error</h6>
<p class="mb-0">${escapeHtml(file.processingError)}</p>
</div>
`;
}
if (file.processingErrors && file.processingErrors.length > 0) {
html += `
<div class="card">
<div class="card-header">
<h6 class="mb-0">Chunk Errors (${file.processingErrors.length})</h6>
</div>
<div class="card-body" style="max-height: 300px; overflow-y: auto;">
`;
file.processingErrors.forEach((error, index) => {
html += `
<div class="border-bottom pb-2 mb-2">
<strong>Chunk ${error.chunkIndex + 1}:</strong><br>
<small class="text-danger">${escapeHtml(error.error)}</small><br>
<small class="text-muted">${escapeHtml(error.chunk)}</small>
</div>
`;
});
html += `
</div>
</div>
`;
}
detailsContent.innerHTML = html;
} else {
detailsContent.innerHTML = `
<div class="alert alert-danger">
<i class="fas fa-exclamation-circle me-2"></i>
Error loading processing details: ${result.error}
</div>
`;
}
} catch (error) {
console.error('Error loading processing details:', error);
document.getElementById('processing-details-content').innerHTML = `
<div class="alert alert-danger">
<i class="fas fa-exclamation-circle me-2"></i>
Error loading processing details: ${error.message}
</div>
`;
}
}
// Progress monitoring for processing files
let progressMonitoring = {};
function startProgressMonitoring() {
// Find all processing files and start monitoring them
const processingCards = document.querySelectorAll('.card');
processingCards.forEach(card => {
const badge = card.querySelector('.badge');
if (badge && badge.textContent && badge.textContent.includes('Processing')) {
// Extract file ID from the card's buttons
const buttons = card.querySelectorAll('button[onclick*="Details"]');
if (buttons.length > 0) {
const onclick = buttons[0].getAttribute('onclick');
const fileIdMatch = onclick.match(/viewProcessingDetails\('([^']+)'\)/);
if (fileIdMatch) {
const fileId = fileIdMatch[1];
startFileProgressMonitoring(fileId);
}
}
}
});
}
function startFileProgressMonitoring(fileId) {
if (progressMonitoring[fileId]) {
clearInterval(progressMonitoring[fileId]);
}
console.log(`Starting progress monitoring for file: ${fileId}`);
progressMonitoring[fileId] = setInterval(async () => {
try {
const response = await fetch(`/api/files/${fileId}/progress`);
const result = await response.json();
if (result.success) {
updateProgressDisplay(fileId, result.progress);
// Stop monitoring if processing is complete
if (result.progress.status !== 'processing') {
clearInterval(progressMonitoring[fileId]);
delete progressMonitoring[fileId];
// Refresh page to show final status
setTimeout(() => {
location.reload();
}, 2000);
}
}
} catch (error) {
console.error('Error checking progress:', error);
}
}, 2000); // Check every 2 seconds
}
function updateProgressDisplay(fileId, progress) {
console.log('Updating progress for', fileId, progress);
// Find the card for this file
const cards = document.querySelectorAll('.card');
let targetCard = null;
cards.forEach(card => {
const buttons = card.querySelectorAll('button[onclick*="Details"]');
if (buttons.length > 0) {
const onclick = buttons[0].getAttribute('onclick');
if (onclick.includes(fileId)) {
targetCard = card;
}
}
});
if (!targetCard) {
console.warn('Target card not found for file:', fileId);
return;
}
// Update the badge with progress information
const badge = targetCard.querySelector('.badge');
if (badge && progress.processingProgress) {
const { currentChunk, totalChunks, percentage } = progress.processingProgress;
badge.innerHTML = `
<i class="fas fa-spinner fa-spin me-1"></i>
Processing ${currentChunk}/${totalChunks} (${percentage}%)
`;
badge.className = 'badge bg-warning text-dark';
} else if (badge && progress.status === 'processed') {
badge.innerHTML = `<i class="fas fa-check-circle me-1"></i>Processed`;
badge.className = 'badge bg-success';
} else if (badge && progress.status === 'failed') {
badge.innerHTML = `<i class="fas fa-exclamation-triangle me-1"></i>Failed`;
badge.className = 'badge bg-danger';
}
// Update or add progress bar
const cardBody = targetCard.querySelector('.card-body');
let progressContainer = cardBody.querySelector('.progress-container');
if (progress.processingProgress) {
if (!progressContainer) {
progressContainer = document.createElement('div');
progressContainer.className = 'progress-container mt-2';
cardBody.appendChild(progressContainer);
}
const { currentChunk, totalChunks, percentage } = progress.processingProgress;
progressContainer.innerHTML = `
<div class="progress mb-2" style="height: 8px;">
<div class="progress-bar progress-bar-striped progress-bar-animated"
role="progressbar"
style="width: ${percentage}%"
aria-valuenow="${percentage}"
aria-valuemin="0"
aria-valuemax="100">
</div>
</div>
<small class="text-muted">
<i class="fas fa-puzzle-piece me-1"></i>
Processing chunk ${currentChunk} of ${totalChunks}
</small>
`;
} else if (progressContainer && (progress.status === 'processed' || progress.status === 'failed')) {
// Remove progress bar when processing is complete
progressContainer.remove();
}
}
function stopAllProgressMonitoring() {
Object.keys(progressMonitoring).forEach(fileId => {
clearInterval(progressMonitoring[fileId]);
delete progressMonitoring[fileId];
});
}
// Clean up when page unloads
window.addEventListener('beforeunload', stopAllProgressMonitoring);
// Auto-refresh processing status every 10 seconds for files that are still processing
document.addEventListener('DOMContentLoaded', function() {
// Start progress monitoring for processing files
startProgressMonitoring();
// Check if there are processing files by looking for badges with "Processing" text
const badges = document.querySelectorAll('.badge');
let hasProcessingFiles = false;
badges.forEach(badge => {
if (badge && badge.textContent && badge.textContent.includes('Processing')) {
hasProcessingFiles = true;
}
});
if (hasProcessingFiles) {
console.log('Found processing files, setting up auto-refresh...');
setInterval(() => {
// Check again if there are still processing files
const currentBadges = document.querySelectorAll('.badge');
let stillProcessing = false;
currentBadges.forEach(badge => {
if (badge && badge.textContent && badge.textContent.includes('Processing')) {
stillProcessing = true;
}
});
if (stillProcessing) {
console.log('Still have processing files, refreshing page...');
location.reload();
}
}, 10000); // Check every 10 seconds
}
});
</script>
<%- include('partials/footer') %>