Certainly! Here's a continuation and completion of the JavaScript code for your GST reconciliation tool, including handling file uploads, parsing Excel/CSV files, reconciling the data, updating the results, tab functionality, filtering/searching, and exporting results.
To parse Excel/CSV files, we'll use SheetJS (xlsx) which is a popular JS library for Excel parsing. I'll include the CDN for SheetJS and complete the scripting.
Full <script> continuation and completion:
<!-- Add SheetJS CDN before your script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
// DOM Elements
const gstr2aFileInput = document.getElementById('gstr2a-file');
const booksFileInput = document.getElementById('books-file');
const gstr2aUploadBtn = document.getElementById('gstr2a-upload-btn');
const booksUploadBtn = document.getElementById('books-upload-btn');
const reconcileBtn = document.getElementById('reconcile-btn');
const resetBtn = document.getElementById('reset-btn');
const exportBtn = document.getElementById('export-btn');
const resultSection = document.getElementById('result-section');
const loader = document.getElementById('loader');
const tabs = document.querySelectorAll('.tab');
const tabContents = document.querySelectorAll('.tab-content');
const searchInput = document.getElementById('search-input');
const statusFilter = document.getElementById('status-filter');
const dateFilter = document.getElementById('date-filter');
const amountFilter = document.getElementById('amount-filter');
const progressContainer = document.getElementById('progress-container');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
// Summary elements
const matchedCount = document.getElementById('matched-count');
const unMatchedGstrCount = document.getElementById('unmatched-gstr-count');
const unMatchedBooksCount = document.getElementById('unmatched-books-count');
const matchedAmount = document.getElementById('matched-amount');
const unMatchedGstrAmount = document.getElementById('unmatched-gstr-amount');
const unMatchedBooksAmount = document.getElementById('unmatched-books-amount');
// Table bodies
const allTableBody = document.getElementById('all-table-body');
const matchedTableBody = document.getElementById('matched-table-body');
const unmatchedGstrTableBody = document.getElementById('unmatched-gstr-table-body');
const unmatchedBooksTableBody = document.getElementById('unmatched-books-table-body');
// Empty states
const allEmptyState = document.getElementById('all-empty-state');
const matchedEmptyState = document.getElementById('matched-empty-state');
const unmatchedGstrEmptyState = document.getElementById('unmatched-gstr-empty-state');
const unmatchedBooksEmptyState = document.getElementById('unmatched-books-empty-state');
// Store parsed data
let gstr2aData = null;
let booksData = null;
let reconciledData = [];
// Utility function to read Excel/CSV files
function readFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = function(e) {
const data = e.target.result;
let workbook;
let arr = new Uint8Array(data);
try {
workbook = XLSX.read(arr, {type: 'array'});
} catch (err) {
reject('Error parsing file: ' + err.message);
}
if (workbook) {
// Use first sheet
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const json = XLSX.utils.sheet_to_json(worksheet, {defval: ''}); // defval ensures empty cells are blank strings
resolve(json);
}
};
reader.onerror = function() {
reject('Failed to read file');
};
reader.readAsArrayBuffer(file);
});
}
// Attach file input to upload buttons for user convenience
gstr2aUploadBtn.addEventListener('click', () => gstr2aFileInput.click());
booksUploadBtn.addEventListener('click', () => booksFileInput.click());
// Handle GSTR-2A file selection
gstr2aFileInput.addEventListener('change', async function() {
const file = this.files[0];
if (!file) return;
gstr2aUploadBtn.textContent = 'Uploading...';
try {
gstr2aData = await readFile(file);
alert('GSTR-2A file uploaded successfully.');
} catch (err) {
alert(err);
gstr2aData = null;
}
gstr2aUploadBtn.textContent = 'Upload GSTR-2A File';
});
// Handle Books file selection
booksFileInput.addEventListener('change', async function() {
const file = this.files[0];
if (!file) return;
booksUploadBtn.textContent = 'Uploading...';
try {
booksData = await readFile(file);
alert('Books file uploaded successfully.');
} catch (err) {
alert(err);
booksData = null;
}
booksUploadBtn.textContent = 'Upload Books File';
});
// Helper: parse date string to JS Date - attempts multiple formats
function parseDate(dateStr) {
if (!dateStr) return null;
// Try Date constructor directly
let d = new Date(dateStr);
if (!isNaN(d)) return d;
// For Excel serialized date (number), convert accordingly
if (typeof dateStr === 'number') {
return XLSX.SSF.parse_date_code(dateStr);
}
return null;
}
// Normalize and key function to enable matching invoices
// Key based on Invoice Number + Supplier GSTIN + maybe date
function getInvoiceKey(invoice) {
const invNo = (invoice['Invoice No'] || invoice['Invoice Number'] || invoice['InvoiceNo'] || invoice['Invoice'] || '').toString().trim().toUpperCase();
const gstin = (invoice['Supplier GSTIN'] || invoice['GSTIN'] || invoice['GSTIN/UIN of Supplier'] || invoice['GSTIN of Supplier'] || '').toString().trim().toUpperCase();
// Optionally, could include date for more strict matching
return invNo + '|' + gstin;
}
// Sum of taxes helper
function getTotalTax(invoice) {
const igst = parseFloat(invoice['IGST'] || invoice['Igst Amount'] || invoice['Integrated Tax'] || 0) || 0;
const cgst = parseFloat(invoice['CGST'] || invoice['Cgst Amount'] || invoice['Central Tax'] || 0) || 0;
const sgst = parseFloat(invoice['SGST'] || invoice['Sgst Amount'] || invoice['State Tax'] || 0) || 0;
return igst + cgst + sgst;
}
function getTaxableValue(invoice) {
return parseFloat(invoice['Taxable Value'] || invoice['Taxable Amount'] || invoice['Taxable'] || 0) || 0;
}
// Format amount to two decimals
function formatAmount(val) {
return val.toFixed(2);
}
// Clear all existing table rows
function clearTables() {
allTableBody.innerHTML = '';
matchedTableBody.innerHTML = '';
unmatchedGstrTableBody.innerHTML = '';
unmatchedBooksTableBody.innerHTML = '';
}
// Create a table row for an invoice
function createRow(invoice, status) {
const tr = document.createElement('tr');
// For all invoices tab only, show status
if (status) {
const statusTd = document.createElement('td');
const spanStatus = document.createElement('span');
spanStatus.classList.add('status-badge');
if (status === 'matched') {
spanStatus.classList.add('status-matched');
spanStatus.textContent = 'Matched';
} else if (status === 'unmatched-gstr') {
spanStatus.classList.add('status-unmatched');
spanStatus.textContent = 'In GSTR-2A Only';
} else if (status === 'unmatched-books') {
spanStatus.classList.add('status-missing');
spanStatus.textContent = 'In Books Only';
} else {
spanStatus.textContent = '-';
}
statusTd.appendChild(spanStatus);
tr.appendChild(statusTd);
}
function addCell(text) {
const td = document.createElement('td');
td.textContent = text || '';
return td;
}
const invoiceNo = invoice['Invoice No'] || invoice['Invoice Number'] || invoice['InvoiceNo'] || invoice['Invoice'] || '';
const dateVal = invoice['Date'] || invoice['Invoice Date'] || invoice['Tax Invoice Date'] || '';
const supplierGSTIN = invoice['Supplier GSTIN'] || invoice['GSTIN'] || invoice['GSTIN/UIN of Supplier'] || invoice['GSTIN of Supplier'] || '';
const supplierName = invoice['Supplier Name'] || invoice['Supplier'] || invoice['Supplier Legal Name'] || '';
const taxableVal = formatAmount(getTaxableValue(invoice));
const igst = formatAmount(parseFloat(invoice['IGST'] || invoice['Igst Amount'] || invoice['Integrated Tax'] || 0) || 0);
const cgst = formatAmount(parseFloat(invoice['CGST'] || invoice['Cgst Amount'] || invoice['Central Tax'] || 0) || 0);
const sgst = formatAmount(parseFloat(invoice['SGST'] || invoice['Sgst Amount'] || invoice['State Tax'] || 0) || 0);
const totalTax = formatAmount(getTotalTax(invoice));
if (!status) {
// All invoices tab includes status as first column - so add status cell here
tr.appendChild(addCell(''));
}
if (status === 'matched') {
// Matched tab does not have status column
tr.appendChild(addCell(invoiceNo));
} else if (status === 'unmatched-gstr' || status === 'unmatched-books') {
tr.appendChild(addCell(invoiceNo));
} else {
// All tab: add status cell already done above
tr.appendChild(addCell(invoiceNo));
}
tr.appendChild(addCell(dateVal));
tr.appendChild(addCell(supplierGSTIN));
tr.appendChild(addCell(supplierName));
tr.appendChild(addCell(taxableVal));
tr.appendChild(addCell(igst));
tr.appendChild(addCell(cgst));
tr.appendChild(addCell(sgst));
tr.appendChild(addCell(totalTax));
return tr;
}
// Main reconciliation function
function reconcile() {
if (!gstr2aData || !booksData) {
alert('Please upload both GSTR-2A and Books files before reconciling.');
return;
}
progressContainer.style.display = 'block';
progressBar.style.width = '0%';
progressText.textContent = 'Reconciling data...';
loader.style.display = 'block';
setTimeout(() => {
// Build maps for efficient lookups keyed by Invoice No + Supplier GSTIN
const gstrMap = new Map();
gstr2aData.forEach(inv => {
const key = getInvoiceKey(inv);
gstrMap.set(key, inv);
});
const booksMap = new Map();
booksData.forEach(inv => {
const key = getInvoiceKey(inv);
booksMap.set(key, inv);
});
const matched = [];
const unmatchedGstr = [];
const unmatchedBooks = [];
// Identify matched and unmatched in GSTR-2A
gstrMap.forEach((inv, key) => {
if (booksMap.has(key)) {
matched.push({gstr: inv, books: booksMap.get(key)});
booksMap.delete(key);
} else {
unmatchedGstr.push(inv);
}
});
// Remaining in booksMap are unmatched in books
booksMap.forEach((inv) => {
unmatchedBooks.push(inv);
});
// Prepare reconciledData as unified list with status
reconciledData = [];
matched.forEach(pair => {
reconciledData.push({
status: 'matched',
invoice: pair.gstr // Use GSTR-2A invoice for display
});
});
unmatchedGstr.forEach(inv => {
reconciledData.push({
status: 'unmatched-gstr',
invoice: inv
});
});
unmatchedBooks.forEach(inv => {
reconciledData.push({
status: 'unmatched-books',
invoice: inv
});
});
// Update summary boxes
matchedCount.textContent = matched.length;
unMatchedGstrCount.textContent = unmatchedGstr.length;
unMatchedBooksCount.textContent = unmatchedBooks.length;
const totalAmount = (list) => list.reduce((acc, inv) => acc + getTotalTax(inv), 0);
matchedAmount.textContent = formatAmount(matched.reduce((acc, pair) => acc + getTotalTax(pair.gstr), 0));
unMatchedGstrAmount.textContent = formatAmount(totalAmount(unmatchedGstr));
unMatchedBooksAmount.textContent = formatAmount(totalAmount(unmatchedBooks));
// Display results
resultSection.style.display = 'block';
populateTables(reconciledData);
loader.style.display = 'none';
progressContainer.style.display = 'none';
}, 500); // Small delay for UX
}
// Populate the tables based on data and filters/search
function populateTables(data) {
clearTables();
// Filter and search data according to UI inputs
const searchValue = searchInput.value.trim().toLowerCase();
const statusVal = statusFilter.value;
const dateVal = dateFilter.value;
const amountVal = amountFilter.value;
// Filter data by status
let filteredData = data;
if (statusVal === 'matched') {
filteredData = filteredData.filter(item => item.status === 'matched');
} else if (statusVal === 'gstr-only') {
filteredData = filteredData.filter(item => item.status === 'unmatched-gstr');
} else if (statusVal === 'books-only') {
filteredData = filteredData.filter(item => item.status === 'unmatched-books');
}
// Filter by date
if (dateVal !== 'all') {
const now = new Date();
let startDate, endDate;
function parseInvoiceDate(inv) {
let d = inv['Date'] || inv['Invoice Date'] || inv['Tax Invoice Date'] || '';
if (!d) return null;
let dt = new Date(d);
if (isNaN(dt) && typeof d === 'number') {
dt = XLSX.SSF.parse_date_code(d);
if (dt) return new Date(dt.y, dt.m - 1, dt.d);
return null;
}
return dt;
}
if (dateVal === 'current-month') {
startDate = new Date(now.getFullYear(), now.getMonth(), 1);
endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);
} else if (dateVal === 'last-month') {
startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
endDate = new Date(now.getFullYear(), now.getMonth(), 0);
} else if (dateVal === 'custom') {
// If you want advanced custom date picker, implement here
// For now, just skip.
}
if (startDate && endDate) {
filteredData = filteredData.filter(item => {
const invDate = parseInvoiceDate(item.invoice);
if (!invDate) return false;
return invDate >= startDate && invDate <= endDate;
});
}
}
// Filter by amount
if (amountVal !== 'all') {
filteredData.sort((a, b) => {
const aAmount = getTotalTax(a.invoice);
const bAmount = getTotalTax(b.invoice);
if (amountVal === 'high-to-low') return bAmount - aAmount;
else return aAmount - bAmount;
});
}
// Filter by search
if (searchValue) {
filteredData = filteredData.filter(item => {
const inv = item.invoice;
const invoiceNo = (inv['Invoice No'] || inv['Invoice Number'] || '').toString().toLowerCase();
const gstin = (inv['Supplier GSTIN'] || inv['GSTIN'] || '').toString().toLowerCase();
const supplier = (inv['Supplier Name'] || inv['Supplier'] || '').toString().toLowerCase();
return invoiceNo.includes(searchValue) || gstin.includes(searchValue) || supplier.includes(searchValue);
});
}
// Clear previous rows
clearTables();
// Track counts per tab for empty state
let hasAll = filteredData.length > 0;
let hasMatched = filteredData.some(i => i.status === 'matched');
let hasUnmatchedGstr = filteredData.some(i => i.status === 'unmatched-gstr');
let hasUnmatchedBooks = filteredData.some(i => i.status === 'unmatched-books');
// Populate All tab
filteredData.forEach(item => {
const row = createRow(item.invoice, item.status);
allTableBody.appendChild(row);
});
allEmptyState.style.display = hasAll ? 'none' : 'block';
// Populate Matched tab
const matchedItems = filteredData.filter(i => i.status === 'matched');
matchedItems.forEach(item => {
const row = createRow(item.invoice);
matchedTableBody.appendChild(row);
});
matchedEmptyState.style.display = matchedItems.length ? 'none' : 'block';
// Populate GSTR only tab
const unmatchedGstrItems = filteredData.filter(i => i.status === 'unmatched-gstr');
unmatchedGstrItems.forEach(item => {
const row = createRow(item.invoice);
unmatchedGstrTableBody.appendChild(row);
});
unmatchedGstrEmptyState.style.display = unmatchedGstrItems.length ? 'none' : 'block';
// Populate Books only tab
const unmatchedBooksItems = filteredData.filter(i => i.status === 'unmatched-books');
unmatchedBooksItems.forEach(item => {
const row = createRow(item.invoice);
unmatchedBooksTableBody.appendChild(row);
});
unmatchedBooksEmptyState.style.display = unmatchedBooksItems.length ? 'none' : 'block';
}
// Reset button handler
resetBtn.addEventListener('click', () => {
if (confirm('Are you sure you want to reset all data?')) {
gstr2aData = null;
booksData = null;
reconciledData = [];
resultSection.style.display = 'none';
gstr2aFileInput.value = '';
booksFileInput.value = '';
searchInput.value = '';
statusFilter.value = 'all';
dateFilter.value = 'all';
amountFilter.value = 'all';
alert('Data has been reset.');
}
});
// Reconcile button handler
reconcileBtn.addEventListener('click', () => {
reconcile();
});
// Tab switching functionality
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const target = tab.getAttribute('data-tab');
tabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
tabContents.forEach(content => {
content.classList.remove('active');
if (content.id === target + '-tab') {
content.classList.add('active');
}
});
});
});
// Filters and search handlers - update tables on change/input
searchInput.addEventListener('input', () => {
if (reconciledData.length) populateTables(reconciledData);
});
statusFilter.addEventListener('change', () => {
if (reconciledData.length) populateTables(reconciledData);
});
dateFilter.addEventListener('change', () => {
if (reconciledData.length) populateTables(reconciledData);
});
amountFilter.addEventListener('change', () => {
if (reconciledData.length) populateTables(reconciledData);
});
// Export results button handler - exports currently filtered & searched data as CSV
exportBtn.addEventListener('click', () => {
if (!reconciledData.length) {
alert('No data to export!');
return;
}
// Export current filtered data from populateTables filtering logic duplicated here
let exportData = reconciledData;
const searchValue = searchInput.value.trim().toLowerCase();
const statusVal = statusFilter.value;
const dateVal = dateFilter.value;
const amountVal = amountFilter.value;
if (statusVal !== 'all') {
if (statusVal === 'matched') exportData = exportData.filter(i => i.status === 'matched');
else if (statusVal === 'gstr-only') exportData = exportData.filter(i => i.status === 'unmatched-gstr');
else if (statusVal === 'books-only') exportData = exportData.filter(i => i.status === 'unmatched-books');
}
// Date filtering (same as above)
if (dateVal !== 'all') {
const now = new Date();
let startDate, endDate;
if (dateVal === 'current-month') {
startDate = new Date(now.getFullYear(), now.getMonth(), 1);
endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);
} else if (dateVal === 'last-month') {
startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
endDate = new Date(now.getFullYear(), now.getMonth(), 0);
}
if (startDate && endDate) {
exportData = exportData.filter(item => {
const invDate = new Date(item.invoice['Date'] || item.invoice['Invoice Date'] || '');
if (!invDate) return false;
return invDate >= startDate && invDate <= endDate;
});
}
}
if (amountVal !== 'all') {
exportData.sort((a, b) => {
const aAmount = getTotalTax(a.invoice);
const bAmount = getTotalTax(b.invoice);
if (amountVal === 'high-to-low') return bAmount - aAmount;
else return aAmount - bAmount;
});
}
if (searchValue) {
exportData = exportData.filter(item => {
const inv = item.invoice;
const invoiceNo = (inv['Invoice No'] || inv['Invoice Number'] || '').toString().toLowerCase();
const gstin = (inv['Supplier GSTIN'] || inv['GSTIN'] || '').toString().toLowerCase();
const supplier = (inv['Supplier Name'] || inv['Supplier'] || '').toString().toLowerCase();
return invoiceNo.includes(searchValue) || gstin.includes(searchValue) || supplier.includes(searchValue);
});
}
if (exportData.length === 0) {
alert('No data available to export based on the current filters.');
return;
}
// Prepare CSV data
const headers = ['Status', 'Invoice No', 'Date', 'Supplier GSTIN', 'Supplier Name', 'Taxable Value', 'IGST', 'CGST', 'SGST', 'Total Tax'];
let csvContent = headers.join(',') + '\n';
exportData.forEach(item => {
const inv = item.invoice;
const row = [
item.status === 'matched' ? 'Matched' :
(item.status === 'unmatched-gstr' ? 'In GSTR-2A Only' : 'In Books Only'),
(inv['Invoice No'] || inv['Invoice Number'] || '').toString().replace(/,/g, ''),
(inv['Date'] || inv['Invoice Date'] || '').toString().replace(/,/g, ''),
(inv['Supplier GSTIN'] || inv['GSTIN'] || '').toString().replace(/,/g, ''),
(inv['Supplier Name'] || inv['Supplier'] || '').toString().replace(/,/g, ''),
formatAmount(getTaxableValue(inv)),
formatAmount(parseFloat(inv['IGST'] || 0)),
formatAmount(parseFloat(inv['CGST'] || 0)),
formatAmount(parseFloat(inv['SGST'] || 0)),
formatAmount(getTotalTax(inv)),
];
csvContent += row.join(',') + '\n';
});
const blob = new Blob([csvContent], {type: 'text/csv;charset=utf-8;'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'gst_reconciliation_results.csv';
a.click();
URL.revokeObjectURL(url);
});
});
</script>
Summary of what this script does:
- Enables file uploads by clicking buttons (linked to hidden file inputs).
- Parses uploaded Excel/CSV files with SheetJS.
- Maps invoices from GSTR-2A and Books using Invoice No and Supplier GSTIN as key.
- Reconciles the data to find matches, GSTR-only, and Books-only invoices.
- Updates the summary panel with counts and amounts.
- Populates multiple tables across tabs with this data.
- Implements tab switching functionality.
- Implements filtering by status, date, amount and search by invoice no, GSTIN, or supplier name.
- Provides an export button to download filtered results as CSV.
- Implements Reset button to clear data and UI.
- Gracefully handles errors and prompts users accordingly.
Note:
- Parsing dates is attempted flexibly but may require adjustment depending on your actual file date formats.
- You might want to enhance date filtering by adding a custom date picker when 'Custom Range' is selected.
- The reconciliation key can be adjusted if your invoice identifiers differ.
- SheetJS CDN version can be updated as required.
Feel free to test this script with your prepared sample Excel/CSV files! If you want, I can also help with adding the custom date range picker or any other functionality.