Spaces:
Running
Running
File size: 15,914 Bytes
923bfa5 54677d9 923bfa5 54677d9 8d57322 54677d9 8d57322 54677d9 8d57322 54677d9 af6686b c48ee34 af6686b c48ee34 59cae93 54677d9 59cae93 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 |
document.addEventListener('DOMContentLoaded', function() {
initCharts();
// Initialize charts
function initCharts() {
// Revenue Line Chart
const revenueCtx = document.getElementById('revenueChart');
if (revenueCtx) {
new Chart(revenueCtx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'],
datasets: [{
label: 'Revenue',
data: [12000, 19000, 15000, 18000, 21000, 25000, 22000, 28000, 26000, 30000],
borderColor: '#6366f1',
backgroundColor: 'rgba(99, 102, 241, 0.1)',
borderWidth: 2,
tension: 0.4,
fill: true
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
}
},
scales: {
y: {
beginAtZero: true,
grid: {
display: true,
color: 'rgba(0, 0, 0, 0.05)'
}
},
x: {
grid: {
display: false
}
}
}
}
});
}
// Expense Doughnut Chart
const expenseCtx = document.getElementById('expenseChart');
if (expenseCtx) {
new Chart(expenseCtx, {
type: 'doughnut',
data: {
labels: ['Supplies', 'Software', 'Marketing', 'Salaries', 'Office'],
datasets: [{
data: [12000, 8000, 5000, 30000, 7000],
backgroundColor: [
'#6366f1',
'#8b5cf6',
'#ec4899',
'#f97316',
'#10b981'
],
borderWidth: 0
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'right'
}
},
cutout: '70%'
}
});
}
}
// Initialize tooltips
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl);
});
// Dark mode toggle functionality
const darkModeToggle = document.getElementById('darkModeToggle');
if (darkModeToggle) {
darkModeToggle.addEventListener('click', function() {
document.documentElement.classList.toggle('dark');
localStorage.setItem('darkMode', document.documentElement.classList.contains('dark'));
});
}
// Check for saved dark mode preference
if (localStorage.getItem('darkMode') === 'true') {
document.documentElement.classList.add('dark');
}
// Invoice generation form handling
const invoiceForm = document.getElementById('invoiceForm');
if (invoiceForm) {
invoiceForm.addEventListener('submit', function(e) {
e.preventDefault();
// Process form data and generate invoice
console.log('Generating invoice...');
});
}
// Responsive sidebar toggle
document.addEventListener('click', function(e) {
if (e.target.closest('#sidebarToggle')) {
document.querySelector('custom-sidebar').classList.toggle('-translate-x-full');
}
});
// Handle form submissions
document.querySelectorAll('form').forEach(form => {
form.addEventListener('submit', function(e) {
e.preventDefault();
// Show loading state
const submitBtn = form.querySelector('button[type="submit"]');
if (submitBtn) {
const originalText = submitBtn.innerHTML;
submitBtn.innerHTML = '<div class="loading-spinner"></div> Processing...';
submitBtn.disabled = true;
// Simulate API call
setTimeout(() => {
submitBtn.innerHTML = originalText;
submitBtn.disabled = false;
alert('Form submitted successfully!');
}, 1500);
}
});
});
});
// AI Processor functionality
document.addEventListener('DOMContentLoaded', function() {
const documentUpload = document.getElementById('documentUpload');
const uploadedDocuments = document.getElementById('uploadedDocuments');
const aiPreviewContainer = document.getElementById('aiPreviewContainer');
const processBtn = document.getElementById('processBtn');
// Handle document upload for AI processor
if (documentUpload) {
documentUpload.addEventListener('change', function(e) {
const files = Array.from(e.target.files);
if (files.length === 0) return;
aiPreviewContainer.classList.remove('hidden');
uploadedDocuments.innerHTML = '';
files.forEach(file => {
const fileContainer = document.createElement('div');
fileContainer.className = 'bg-gray-50 rounded-lg p-4 flex items-start';
const fileIcon = document.createElement('div');
fileIcon.className = 'w-10 h-10 bg-indigo-100 rounded-full flex items-center justify-center mr-3 flex-shrink-0';
let iconName = 'file';
if (file.type.match('image.*')) iconName = 'image';
else if (file.type === 'application/pdf') iconName = 'file-text';
else if (file.type.match('word')) iconName = 'file-text';
fileIcon.innerHTML = `<i data-feather="${iconName}" class="text-indigo-600"></i>`;
const fileInfo = document.createElement('div');
fileInfo.className = 'flex-1 min-w-0';
const fileName = document.createElement('p');
fileName.className = 'text-sm font-medium text-gray-900 truncate';
fileName.textContent = file.name;
const fileDetails = document.createElement('div');
fileDetails.className = 'flex items-center text-xs text-gray-500 mt-1';
fileDetails.innerHTML = `
<span>${(file.size / 1024).toFixed(2)} KB</span>
<span class="mx-2">•</span>
<span>${file.type}</span>
`;
fileInfo.appendChild(fileName);
fileInfo.appendChild(fileDetails);
fileContainer.appendChild(fileIcon);
fileContainer.appendChild(fileInfo);
uploadedDocuments.appendChild(fileContainer);
feather.replace();
});
});
}
// Process button handler
if (processBtn) {
processBtn.addEventListener('click', async function() {
const files = documentUpload.files;
if (files.length === 0) {
alert('Please upload documents first');
return;
}
processBtn.innerHTML = '<div class="loading-spinner"></div> Processing...';
processBtn.disabled = true;
// Simulate AI processing
setTimeout(() => {
processBtn.innerHTML = '<i data-feather="check" class="mr-2"></i> Processing Complete';
feather.replace();
alert('Documents processed successfully! Extracted data can now be reviewed.');
}, 3000);
});
}
});
// File upload and processing
document.addEventListener('DOMContentLoaded', function() {
const invoiceUpload = document.getElementById('invoiceUpload');
const uploadedFiles = document.getElementById('uploadedFiles');
const previewContainer = document.getElementById('previewContainer');
const scanBtn = document.getElementById('scanBtn');
// Handle file upload
invoiceUpload.addEventListener('change', function(e) {
const files = Array.from(e.target.files);
if (files.length === 0) return;
previewContainer.classList.remove('hidden');
uploadedFiles.innerHTML = '';
files.forEach(file => {
const fileContainer = document.createElement('div');
fileContainer.className = 'bg-gray-50 rounded-lg p-3 flex items-center';
const fileIcon = document.createElement('div');
fileIcon.className = 'w-10 h-10 bg-indigo-100 rounded-full flex items-center justify-center mr-3';
fileIcon.innerHTML = '<i data-feather="file" class="text-indigo-600"></i>';
const fileInfo = document.createElement('div');
fileInfo.className = 'flex-1 min-w-0';
const fileName = document.createElement('p');
fileName.className = 'text-sm font-medium text-gray-900 truncate';
fileName.textContent = file.name;
const fileSize = document.createElement('p');
fileSize.className = 'text-xs text-gray-500';
fileSize.textContent = `${(file.size / 1024).toFixed(2)} KB`;
fileInfo.appendChild(fileName);
fileInfo.appendChild(fileSize);
fileContainer.appendChild(fileIcon);
fileContainer.appendChild(fileInfo);
uploadedFiles.appendChild(fileContainer);
feather.replace();
// Process the file
processUploadedFile(file);
});
});
// Scan button handler
scanBtn.addEventListener('click', function() {
// This would trigger mobile device camera in production
alert('Scanning feature would open device camera to capture invoice');
});
});
// Process uploaded file
async function processUploadedFile(file) {
const reader = new FileReader();
reader.onload = async function(e) {
try {
if (file.type === 'application/pdf') {
// Process PDF
const pdfBytes = new Uint8Array(e.target.result);
const pdfDoc = await PDFLib.PDFDocument.load(pdfBytes);
const textContent = await extractTextFromPDF(pdfDoc);
extractLineItems(textContent);
} else if (file.type.match('image.*')) {
// Process image
const imageText = await extractTextFromImage(e.target.result);
extractLineItems(imageText);
}
} catch (error) {
console.error('Error processing file:', error);
}
};
reader.readAsArrayBuffer(file);
}
// Extract text from PDF
async function extractTextFromPDF(pdfDoc) {
const pages = pdfDoc.getPages();
let textContent = '';
for (const page of pages) {
const text = await page.getTextContent();
textContent += text.items.map(item => item.str).join(' ');
}
return textContent;
}
// Extract text from image using OCR
async function extractTextFromImage(imageData) {
const worker = Tesseract.createWorker();
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize(imageData);
await worker.terminate();
return text;
}
// Extract line items from text
function extractLineItems(text) {
// This is a simplified example - in production you'd use more sophisticated NLP
const lines = text.split('\n');
const items = [];
let foundItems = false;
lines.forEach(line => {
// Simple pattern matching for line items
const itemMatch = line.match(/(\d+)\s+([\w\s]+)\s+(\d+\.\d{2})/i);
if (itemMatch) {
items.push({
description: itemMatch[2].trim(),
quantity: parseInt(itemMatch[1]),
rate: parseFloat(itemMatch[3]),
amount: parseInt(itemMatch[1]) * parseFloat(itemMatch[3])
});
foundItems = true;
}
// Look for totals
const totalMatch = line.match(/total.*?(\d+\.\d{2})/i);
if (totalMatch) {
console.log('Found total:', totalMatch[1]);
}
});
if (foundItems) {
populateInvoiceItems(items);
}
}
// Populate invoice items table
function populateInvoiceItems(items) {
const tbody = document.querySelector('table tbody');
tbody.innerHTML = '';
items.forEach(item => {
const row = document.createElement('tr');
row.innerHTML = `
<td class="px-6 py-4 whitespace-nowrap">
<input type="text" value="${item.description}" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500">
</td>
<td class="px-6 py-4 whitespace-nowrap">
<input type="number" class="w-20 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500" value="${item.quantity}">
</td>
<td class="px-6 py-4 whitespace-nowrap">
<input type="number" class="w-24 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500" value="${item.rate}">
</td>
<td class="px-6 py-4 whitespace-nowrap">${item.amount.toFixed(2)}</td>
<td class="px-6 py-4 whitespace-nowrap">
<button class="text-red-500 hover:text-red-700">
<i data-feather="trash-2"></i>
</button>
</td>
`;
tbody.appendChild(row);
});
feather.replace();
}
// Enhanced AI processing with real API integration
async function processInvoiceData(data) {
try {
// Using OpenAI API for enhanced processing
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${YOUR_OPENAI_KEY}`
},
body: JSON.stringify({
model: "gpt-4",
messages: [{
role: "system",
content: "You are an expert invoice processing AI. Extract all relevant fields from this invoice data."
}, {
role: "user",
content: JSON.stringify(data)
}],
temperature: 0.2
})
});
const result = await response.json();
return parseAIResponse(result.choices[0].message.content);
} catch (error) {
console.error('AI Processing Error:', error);
return null;
}
}
// New AI features
function initAIFeatures() {
// Smart suggestions
document.querySelectorAll('input').forEach(input => {
input.addEventListener('focus', async () => {
const suggestions = await getAISuggestions(input.name);
showAISuggestions(input, suggestions);
});
});
// Auto-categorization
document.querySelectorAll('.category-select').forEach(select => {
select.addEventListener('change', async (e) => {
if (e.target.value === 'auto') {
const items = getLineItems();
const categories = await predictCategories(items);
applyCategories(categories);
}
});
});
}
// Initialize AI features when DOM loads
document.addEventListener('DOMContentLoaded', initAIFeatures);
|