<div class="tabs">
<div class="tab active" data-tab="upload">Upload Excel</div>
<div class="tab" data-tab="preview">Preview Data</div>
</div>
<div id="upload-tab" class="tab-content active">
<div class="upload-form">
<div class="file-input-group">
<label for="excel_file">Upload Excel file with GSTIN Numbers:</label>
<div class="file-input" id="dropzone">
<p>Drag & drop your file here or click to browse</p>
<input type="file" id="excel_file" accept=".xls,.xlsx">
<div id="file-name" class="file-name"></div>
</div>
</div>
<div class="checkbox-group">
<input type="checkbox" id="reprocess_errors_only" name="reprocess_errors_only" value="1">
<label for="reprocess_errors_only">Reprocess error rows only</label>
</div>
<button type="button" id="upload-btn" class="btn btn-primary">Upload and Preview</button>
</div>
<div id="progress-container" class="progress-container">
<div class="progress-bar">
<div id="progress-bar-fill" class="progress-bar-fill"></div>
</div>
<div id="progress-text" class="progress-text">Processing file...</div>
</div>
<div class="note-section">
<p><strong>Note:</strong> The GSTIN numbers should be in the first column (A) starting from row 2 (row 1 is header).</p>
</div>
</div>
<div id="preview-tab" class="tab-content">
<div id="summary-section" class="summary-section" style="display: none;">
<div class="summary-card">
<h3>Total Records</h3>
<div id="total-count" class="count">0</div>
</div>
<div class="summary-card success">
<h3>Successfully Processed</h3>
<div id="success-count" class="count">0</div>
</div>
<div class="summary-card error">
<h3>Errors</h3>
<div id="error-count" class="count">0</div>
</div>
</div>
<div class="data-table-container">
<table id="preview-table" style="display: none;">
<thead>
<tr>
<th>Action</th>
<th>GST Number</th>
<th>Status</th>
<th>Legal Name</th>
<th>Registration Date</th>
<th>State</th>
<th>Trade Name</th>
<th>Address</th>
<th>Business Type</th>
<th>Nature of Business</th>
<th>Last Updated</th>
</tr>
</thead>
<tbody id="preview-table-body">
<!-- Data will be added here dynamically -->
</tbody>
</table>
<div id="empty-state" class="empty-state">
<div class="icon">📊</div>
<h3>No data to preview</h3>
<p>Please upload an Excel file with GSTIN numbers to see the preview here.</p>
</div>
</div>
<div id="process-actions" style="display: none; margin-top: 20px; text-align: center;">
<button type="button" id="process-all-btn" class="btn btn-success">Process All Pending Records</button>
<button type="button" id="download-btn" class="btn btn-primary" style="margin-left: 10px;">Download Results</button>
</div>
</div>
</div>
<script>
// Mock data for demonstration
const mockGstData = {
'27AADCB2230M1ZT': {
gstNumber: '27AADCB2230M1ZT',
status: 'Active',
legalName: 'ABC Corporation Pvt Ltd',
registrationDate: '12-09-2017',
state: 'Maharashtra',
tradeName: 'ABC Corp',
address: '123, Business Park, Mumbai - 400001',
businessType: 'Private Limited Company',
natureOfBusiness: 'Manufacturing, Trading',
lastUpdated: '2023-06-15'
},
'29AAKCS0956G1Z1': {
status: 'Active',
gstNumber: '29AAKCS0956G1Z1',
legalName: 'XYZ Solutions Private Limited',
registrationDate: '28-07-2017',
state: 'Karnataka',
tradeName: 'XYZ Solutions',
address: '456, Tech Park, Bangalore - 560001',
businessType: 'Private Limited Company',
natureOfBusiness: 'IT Services, Consulting',
lastUpdated: '2023-05-20'
},
'24AAACR5055K1Z5': {
status: 'Cancelled',
gstNumber: '24AAACR5055K1Z5',
legalName: 'PQR Industries Ltd',
registrationDate: '15-08-2017',
state: 'Gujarat',
tradeName: 'PQR Industries',
address: '789, Industrial Area, Ahmedabad - 380015',
businessType: 'Public Limited Company',
natureOfBusiness: 'Manufacturing',
lastUpdated: '2023-04-10'
},
'07BBBCE9882F1Z2': {
error: 'Invalid GSTIN - not found in database'
},
'06AABCU9603R1ZV': {
error: 'Temporary error - please try again later'
}
};
// DOM elements
const errorContainer = document.getElementById('error-container');
const fileInput = document.getElementById('excel_file');
const dropzone = document.getElementById('dropzone');
const fileNameDisplay = document.getElementById('file-name');
const uploadBtn = document.getElementById('upload-btn');
const progressContainer = document.getElementById('progress-container');
const progressBarFill = document.getElementById('progress-bar-fill');
const progressText = document.getElementById('progress-text');
const previewTable = document.getElementById('preview-table');
const previewTableBody = document.getElementById('preview-table-body');
const emptyState = document.getElementById('empty-state');
const processAllBtn = document.getElementById('process-all-btn');
const downloadBtn = document.getElementById('download-btn');
const processActions = document.getElementById('process-actions');
const summarySection = document.getElementById('summary-section');
const totalCount = document.getElementById('total-count');
const successCount = document.getElementById('success-count');
const errorCount = document.getElementById('error-count');
// Tab handling
const tabs = document.querySelectorAll('.tab');
const tabContents = document.querySelectorAll('.tab-content');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const tabId = tab.getAttribute('data-tab');
// Update active tab
tabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
// Show active content
tabContents.forEach(content => {
content.classList.remove('active');
if (content.id === `${tabId}-tab`) {
content.classList.add('active');
}
});
});
});
// File upload handling
fileInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
const fileName = e.target.files[0].name;
fileNameDisplay.textContent = fileName;
dropzone.classList.add('has-file');
} else {
fileNameDisplay.textContent = '';
dropzone.classList.remove('has-file');
}
});
// Drag and drop functionality
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropzone.addEventListener(eventName, preventDefaults, false);
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
['dragenter', 'dragover'].forEach(eventName => {
dropzone.addEventListener(eventName, () => {
dropzone.classList.add('dragover');
}, false);
});
['dragleave', 'drop'].forEach(eventName => {
dropzone.addEventListener(eventName, () => {
dropzone.classList.remove('dragover');
}, false);
});
dropzone.addEventListener('drop', (e) => {
const dt = e.dataTransfer;
const files = dt.files;
if (files.length > 0) {
fileInput.files = files;
const fileName = files[0].name;
fileNameDisplay.textContent = fileName;
dropzone.classList.add('has-file');
}
});
// Click to browse
dropzone.addEventListener('click', () => {
fileInput.click();
});
// Upload and preview functionality
uploadBtn.addEventListener('click', () => {
if (!fileInput.files || fileInput.files.length === 0) {
showError('Please select an Excel file to upload.');
return;
}
const file = fileInput.files[0];
const fileExtension = file.name.split('.').pop().toLowerCase();
if (fileExtension !== 'xls' && fileExtension !== 'xlsx') {
showError('Please upload a valid Excel file (.xls or .xlsx).');
return;
}
// Show progress bar
progressContainer.style.display = 'block';
let progress = 0;
const progressInterval = setInterval(() => {
progress += 5;
if (progress > 90) {
clearInterval(progressInterval);
}
progressBarFill.style.width = `${progress}%`;
progressText.textContent = `Processing file... ${progress}%`;
}, 100);
// Simulate file processing
setTimeout(() => {
clearInterval(progressInterval);
progressBarFill.style.width = '100%';
progressText.textContent = 'Processing complete!';
// Generate random GSTIN data for demonstration
const gstNumberList = [
'27AADCB2230M1ZT',
'29AAKCS0956G1Z1',
'24AAACR5055K1Z5',
'07BBBCE9882F1Z2',
'06AABCU9603R1ZV',
// Generate some random pending records
...Array(5).fill().map(() => generateRandomGSTIN())
];
// Display data preview
displayPreview(gstNumberList);
// Switch to preview tab
document.querySelector('[data-tab="preview"]').click();
// Hide progress after a delay
setTimeout(() => {
progressContainer.style.display = 'none';
}, 1000);
}, 1500);
});
// Process individual row
function processGSTIN(gstinNumber, rowElement) {
const actionButton = rowElement.querySelector('.action-button');
actionButton.textContent = 'Processing...';
actionButton.classList.add('loading');
actionButton.disabled = true;
// Simulate API call
setTimeout(() => {
const result = mockGstData[gstinNumber] || {
gstNumber: gstinNumber,
status: ['Active', 'Cancelled'][Math.floor(Math.random() * 2)],
legalName: `Company ${gstinNumber.substring(0, 5)}`,
registrationDate: `${Math.floor(Math.random() * 28) + 1}-${Math.floor(Math.random() * 12) + 1}-201${Math.floor(Math.random() * 9)}`,
state: ['Maharashtra', 'Karnataka', 'Gujarat', 'Delhi', 'Tamil Nadu'][Math.floor(Math.random() * 5)],
tradeName: `Trade ${gstinNumber.substring(0, 5)}`,
address: `${Math.floor(Math.random() * 999) + 1}, Sample Street, City - ${Math.floor(Math.random() * 900000) + 100000}`,
businessType: ['Private Limited', 'Public Limited', 'Partnership', 'Proprietorship'][Math.floor(Math.random() * 4)],
natureOfBusiness: ['Manufacturing', 'Services', 'Trading', 'Retail', 'Wholesale'][Math.floor(Math.random() * 5)],
lastUpdated: `202${Math.floor(Math.random() * 3) + 1}-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}`
};
// Update row with fetched data
updateTableRow(rowElement, result);
// Update summary counts
updateSummaryCounts();
actionButton.classList.remove('loading');
if (result.error) {
actionButton.textContent = 'Retry';
actionButton.disabled = false;
actionButton.classList.remove('btn-primary');
actionButton.classList.add('btn-warning');
} else {
actionButton.textContent = 'Processed';
actionButton.disabled = true;
}
}, 1000);
}
// Process all pending records
processAllBtn.addEventListener('click', () => {
const pendingRows = document.querySelectorAll('.pending-row');
if (pendingRows.length === 0) {
showError('No pending records to process.');
return;
}
processAllBtn.textContent = 'Processing...';
processAllBtn.disabled = true;
processAllBtn.classList.add('loading');
let processed = 0;
// Process each row with a slight delay between them
pendingRows.forEach((row, index) => {
setTimeout(() => {
const gstinNumber = row.querySelector('td:nth-child(2)').textContent;
processGSTIN(gstinNumber, row);
processed++;
if (processed === pendingRows.length) {
processAllBtn.textContent = 'Process All Pending Records';
processAllBtn.disabled = false;
processAllBtn.classList.remove('loading');
}
}, index * 300);
});
});
// Download results
downloadBtn.addEventListener('click', () => {
// Create a CSV string from table data
const headers = Array.from(document.querySelectorAll('#preview-table th'))
.slice(1) // Skip action column
.map(th => th.textContent)
.join(',');
const rows = [];
document.querySelectorAll('#preview-table tbody tr').forEach(row => {
const rowData = Array.from(row.querySelectorAll('td'))
.slice(1) // Skip action column
.map(td => `"${td.textContent.replace(/"/g, '""')}"`)
.join(',');
rows.push(rowData);
});
const csvContent = `${headers}\n${rows.join('\n')}`;
// Create download link
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', 'gst_details_output.csv');
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
// Helper Functions
function showError(message) {
errorContainer.textContent = message;
errorContainer.style.display = 'block';
// Auto hide after 5 seconds
setTimeout(() => {
errorContainer.style.display = 'none';
}, 5000);
}
function displayPreview(gstinList) {
// Clear existing data
previewTableBody.innerHTML = '';
if (gstinList.length === 0) {
previewTable.style.display = 'none';
emptyState.style.display = 'block';
processActions.style.display = 'none';
summarySection.style.display = 'none';
return;
}
// Add rows for each GSTIN
gstinList.forEach(gstin => {
const row = document.createElement('tr');
row.className = 'pending-row';
// Create cells
const cells = [
`<td class="action-cell"><button class="action-button refresh-button" data-gstin="${gstin}">Process</button></td>`,
`<td>${gstin}</td>`,
`<td>Pending</td>`,
`<td></td>`,
`<td></td>`,
`<td></td>`,
`<td></td>`,
`<td></td>`,
`<td></td>`,
`<td></td>`,
`<td></td>`
];
row.innerHTML = cells.join('');
previewTableBody.appendChild(row);
});
// Add event listeners to process buttons
document.querySelectorAll('.action-button').forEach(button => {
button.addEventListener('click', (e) => {
const gstin = e.target.getAttribute('data-gstin');
const row = e comeplete the code
Certainly! Here's the completed and corrected JavaScript code continuation to properly handle the per-row processing button click event and to finalize the update and interaction functions. This continues from your last line and ensures the functionality you intend:
button.addEventListener('click', (e) => {
const gstin = e.target.getAttribute('data-gstin');
const row = e.target.closest('tr');
processGSTIN(gstin, row);
});
});
// Show table and controls
previewTable.style.display = 'table';
emptyState.style.display = 'none';
processActions.style.display = 'block';
summarySection.style.display = 'flex';
// Update summary counts initially (all pending)
totalCount.textContent = gstinList.length;
successCount.textContent = 0;
errorCount.textContent = 0;
}
function updateTableRow(rowElement, data) {
// Remove pending-row class
rowElement.classList.remove('pending-row');
if (data.error) {
rowElement.classList.add('error-row');
} else {
rowElement.classList.add('success-row');
}
rowElement.innerHTML = `
<td class="action-cell">
${data.error ?
`<button class="action-button btn btn-warning" data-gstin="${data.gstNumber || ''}">Retry</button>` :
`<button class="action-button btn btn-primary" disabled>Processed</button>`
}
</td>
<td>${data.gstNumber || ''}</td>
<td>
<span class="status-badge ${getStatusClass(data.status)}">
${data.status || 'Unknown'}
</span>
</td>
<td>${data.legalName || ''}</td>
<td>${data.registrationDate || ''}</td>
<td>${data.state || ''}</td>
<td>${data.tradeName || ''}</td>
<td>${data.address || ''}</td>
<td>${data.businessType || ''}</td>
<td>${data.natureOfBusiness || ''}</td>
<td>${data.lastUpdated || ''}</td>
`;
// Add event listener for retry button, if present
const retryBtn = rowElement.querySelector('.action-button.btn-warning');
if (retryBtn) {
retryBtn.addEventListener('click', () => {
processGSTIN(data.gstNumber, rowElement);
});
}
}
function getStatusClass(status) {
if (!status) return '';
status = status.toLowerCase();
if (status === 'active') return 'status-active';
if (status === 'cancelled' || status === 'inactive') return 'status-inactive';
if (status === 'pending') return 'status-pending';
return '';
}
function updateSummaryCounts() {
const rows = previewTableBody.querySelectorAll('tr');
let total = rows.length;
let success = 0;
let errors = 0;
rows.forEach(row => {
if (row.classList.contains('success-row')) {
success++;
} else if (row.classList.contains('error-row')) {
errors++;
}
});
totalCount.textContent = total;
successCount.textContent = success;
errorCount.textContent = errors;
}
function generateRandomGSTIN() {
const states = ['01','02','03','04','05','06','07','08','09','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'];
const alphaNum = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let gstin = states[Math.floor(Math.random() * states.length)];
for(let i=0; i < 12; i++) {
gstin += alphaNum.charAt(Math.floor(Math.random() * alphaNum.length));
}
gstin += alphaNum.charAt(Math.floor(Math.random() * alphaNum.length)); // 14th char
gstin += alphaNum.charAt(Math.floor(Math.random() * alphaNum.length)); // 15th char (checksum)
return gstin;
}
</script>
</body>
</html>
Explanation:
- The event listener for the per-row Process/Retry buttons now properly uses
e.target.closest('tr') to get the row element.
- The function
updateTableRow updates the entire row with the GSTIN details or error info.
- Rows with errors get a Retry button that calls
processGSTIN again on click.
- Status badges get colored based on the status using the helper function
getStatusClass.
- Summary counts are refreshed after each row is processed.
generateRandomGSTIN() creates random GSTIN-like strings for mock demonstration.
- All styling and UI bindings correspond to your defined CSS classes.
This should allow your GSTIN Excel upload preview and processing UI to work seamlessly with mock data and simulated asynchronous fetching. Let me know if you want me to help with actual Excel parsing or integration!