uploadte to corect preview and print the labels for 1 row

This commit is contained in:
2025-09-20 17:31:20 +03:00
parent beeaa02c35
commit 2c01db9fea
6 changed files with 865 additions and 120 deletions

View File

@@ -235,14 +235,28 @@ table tbody tr.selected td {
</div>
</div>
</div>
<div style="width: 100%; display: flex; justify-content: center; align-items: center; gap: 12px; margin-top: 18px;">
<label for="print-label-btn" style="font-size: 14px; font-weight: 500; color: var(--app-card-text); margin-bottom: 0;">Print selected order</label>
<button id="print-label-btn" class="btn btn-primary" style="font-size: 14px; padding: 6px 24px;">Print</button>
<!-- PDF Information -->
<div style="width: 100%; margin-top: 15px; padding: 0 15px; text-align: center;">
<div style="background: #e8f4f8; border: 1px solid #bee5eb; border-radius: 6px; padding: 12px; font-size: 11px; color: #0c5460;">
<strong>📄 PDF Label Generation</strong><br>
Labels will be generated as PDF files for universal printing compatibility.<br>
<small style="color: #6c757d;">Works with any browser and printer - no extensions needed!</small>
</div>
</div>
<!-- Print Button Section -->
<div style="width: 100%; display: flex; justify-content: center; align-items: center; gap: 12px; margin-top: 15px;">
<label for="print-label-btn" style="font-size: 14px; font-weight: 500; color: var(--app-card-text); margin-bottom: 0;">Generate PDF Labels (80x110mm)</label>
<button id="print-label-btn" class="btn btn-success" style="font-size: 14px; padding: 8px 28px; border-radius: 6px;">📄 Generate PDF</button>
</div>
<div style="width: 100%; text-align: center; margin-top: 8px; color: #6c757d; font-size: 12px;">
Creates sequential labels based on quantity (e.g., CP00000711-001 to CP00000711-063)
</div>
<div style="width: 100%; text-align: center; margin-top: 12px;">
<a href="{{ url_for('main.download_extension') }}" target="_blank" style="font-size: 12px; color: #007bff; text-decoration: none;">
🔗 Install Direct Print Extension
</a>
<small style="font-size: 11px; color: #6c757d;">
<EFBFBD> PDF labels can be printed directly from your browser or saved for later use
</small>
</div>
</div>
@@ -281,9 +295,24 @@ table tbody tr.selected td {
<script>
document.getElementById('check-db-btn').addEventListener('click', function() {
console.log('Check Database button clicked');
// Show loading state
const button = this;
const originalText = button.textContent;
button.textContent = 'Loading...';
button.disabled = true;
fetch('/get_unprinted_orders')
.then(response => response.json())
.then(response => {
console.log('Response status:', response.status);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log('Received data:', data);
const tbody = document.getElementById('unprinted-orders-table');
tbody.innerHTML = '';
data.forEach((order, index) => {
@@ -354,10 +383,10 @@ document.getElementById('check-db-btn').addEventListener('click', function() {
if (data.length > 0) {
updateLabelPreview(data[0]);
// Add fallback print functionality if extension is not available
addFallbackPrintHandler();
// Auto-select first row
// Add fallback print functionality if extension is not available
addPDFGenerationHandler();
// Auto-select first row
setTimeout(() => {
const firstRow = document.querySelector('.print-module-table tbody tr');
if (firstRow) {
@@ -389,6 +418,20 @@ document.getElementById('check-db-btn').addEventListener('click', function() {
document.getElementById('prod-order-value').textContent = 'Error';
document.getElementById('barcode-text').textContent = 'Error';
document.getElementById('vertical-barcode-text').textContent = '000000-00';
// Reset button state
button.textContent = originalText;
button.disabled = false;
})
.catch(error => {
console.error('Error fetching orders:', error);
// Show error message to user
alert('Failed to load orders from database. Error: ' + error.message);
// Reset button state
button.textContent = originalText;
button.disabled = false;
});
});
@@ -437,80 +480,177 @@ function updateLabelPreview(order) {
document.getElementById('barcode-text').textContent = prodOrder;
}
// Fallback print handler for when Chrome extension is not available
// PDF Generation System - No printer setup needed
// Labels are generated as PDF files for universal compatibility
// Legacy function name - now handles PDF generation
function addFallbackPrintHandler() {
// Check if Chrome extension modified the button
setTimeout(() => {
const printButton = document.getElementById('print-label-btn');
// Initialize PDF print button
const printButton = document.getElementById('print-label-btn');
if (printButton) {
// Update button text and appearance for PDF generation
printButton.innerHTML = '<27> Generate PDF Labels';
printButton.title = 'Generate PDF with multiple labels based on quantity';
// If button text hasn't changed, extension is not active
if (printButton && !printButton.innerHTML.includes('🖨️ Print Direct')) {
console.log('Chrome extension not detected, adding fallback print handler');
printButton.addEventListener('click', function(e) {
e.preventDefault();
// Add fallback event listener
printButton.addEventListener('click', function(e) {
e.preventDefault();
// Get selected order
const selectedRow = document.querySelector('.print-module-table tbody tr.selected');
if (!selectedRow) {
alert('Please select an order first from the table below.');
return;
}
const orderId = selectedRow.dataset.orderId;
const quantityCell = selectedRow.querySelector('td:nth-child(5)'); // Cantitate column
const quantity = quantityCell ? parseInt(quantityCell.textContent) : 1;
const prodOrderCell = selectedRow.querySelector('td:nth-child(2)'); // Comanda Productie column
const prodOrder = prodOrderCell ? prodOrderCell.textContent.trim() : 'N/A';
if (!orderId) {
alert('Could not determine order ID. Please refresh and try again.');
return;
}
// Show loading state
const originalText = this.textContent;
this.textContent = 'Generating PDF...';
this.disabled = true;
console.log(`Generating PDF for order ${orderId} with ${quantity} labels`);
// Generate PDF
fetch(`/generate_labels_pdf/${orderId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.blob();
})
.then(blob => {
// Create download link for PDF
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `labels_${prodOrder}_${quantity}pcs.pdf`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
const labelPreview = document.getElementById('label-preview');
if (!labelPreview) {
alert('Please select an order first.');
return;
// Also open PDF in new tab for printing
const printWindow = window.open(url, '_blank');
printWindow.focus();
// Show success message
alert(`✅ PDF generated successfully!\n📊 Order: ${prodOrder}\n📦 Labels: ${quantity} pieces\n\nThe PDF has been downloaded and opened for printing.`);
// Refresh the orders table to reflect printed status
document.getElementById('check-db-btn').click();
})
.catch(error => {
console.error('Error generating PDF:', error);
alert('❌ Failed to generate PDF labels. Error: ' + error.message);
})
.finally(() => {
// Reset button state
this.textContent = originalText;
this.disabled = false;
});
});
}
}
// PDF generation handler
function addPDFGenerationHandler() {
const printButton = document.getElementById('print-label-btn');
if (printButton) {
printButton.addEventListener('click', function(e) {
e.preventDefault();
// Get selected order
const selectedRow = document.querySelector('.print-module-table tbody tr.selected');
if (!selectedRow) {
alert('Please select an order first from the table below.');
return;
}
const orderId = selectedRow.dataset.orderId;
const prodOrder = selectedRow.querySelector('td:nth-child(2)').textContent.trim();
const quantity = selectedRow.querySelector('td:nth-child(5)').textContent.trim();
if (!orderId) {
alert('Error: Could not determine order ID.');
return;
}
// Show loading state
const originalText = printButton.innerHTML;
printButton.innerHTML = '⏳ Generating PDF...';
printButton.disabled = true;
// Generate PDF
fetch(`/generate_labels_pdf/${orderId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => {
if (!response.ok) {
return response.json().then(data => {
throw new Error(data.error || `HTTP ${response.status}`);
});
}
// Create a new window for printing
const printWindow = window.open('', '_blank');
const printContent = `
<!DOCTYPE html>
<html>
<head>
<title>Quality Recticel Label</title>
<style>
body {
margin: 0;
padding: 20px;
font-family: Arial, sans-serif;
}
.print-container {
width: 210mm;
height: 297mm;
margin: 0 auto;
}
.label-wrapper {
transform: scale(1.2);
transform-origin: top left;
}
@media print {
body { padding: 0; }
.print-container { margin: 0; }
}
</style>
</head>
<body>
<div class="print-container">
<div class="label-wrapper">
${labelPreview.outerHTML}
</div>
</div>
</body>
</html>
`;
// Get filename from response headers or create default
const contentDisposition = response.headers.get('Content-Disposition');
let filename = `labels_${prodOrder}_qty${quantity}.pdf`;
if (contentDisposition) {
const matches = contentDisposition.match(/filename="?([^"]+)"?/);
if (matches) filename = matches[1];
}
printWindow.document.write(printContent);
printWindow.document.close();
return response.blob().then(blob => ({ blob, filename }));
})
.then(({ blob, filename }) => {
// Create download link
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
// Wait for content to load, then print
printWindow.onload = function() {
printWindow.focus();
printWindow.print();
printWindow.close();
};
// Show success message
alert(`✅ PDF generated successfully!\n\n📄 ${quantity} labels created for ${prodOrder}\n📋 Sequential numbering: ${prodOrder}-001 to ${prodOrder}-${String(quantity).padStart(3, '0')}\n📁 File: ${filename}\n\n➡️ The PDF is ready to print from your browser!`);
// Refresh the orders table to show updated print status
setTimeout(() => {
document.getElementById('check-db-btn').click();
}, 1000);
})
.catch(error => {
console.error('PDF generation error:', error);
alert(`❌ Error generating PDF: ${error.message}\n\nPlease try again or contact support.`);
})
.finally(() => {
// Reset button state
printButton.innerHTML = originalText;
printButton.disabled = false;
});
// Update button text to indicate fallback mode
printButton.innerHTML = '🖨️ Print (Browser)';
printButton.title = 'Print using browser dialog - Install Chrome Extension for direct printing';
}
}, 2000); // Wait 2 seconds for extension to load
});
}
}
</script>
{% endblock %}