Certainly! Adding logging to your code will help you monitor the progress and identify any potential issues during execution. Below is your updated TypeScript code with comprehensive console.log statements added to indicate progress at various stages:
import * as fs from 'fs';
import csv from 'csv-parser';
interface Mapping {
sentralColumn: string;
proserveColumn: string;
}
interface ParityReportEntry {
proserveId: string;
sentralId: string;
proserveColumn: string;
sentralColumn: string;
proserveValue: string;
sentralValue: string;
}
async function parseCSV(filePath: string): Promise<any[]> {
console.log(`Starting to parse CSV file: ${filePath}`);
return new Promise((resolve, reject) => {
const results: any[] = [];
const startTime = Date.now();
fs.createReadStream(filePath)
.pipe(csv())
.on('data', (data: any) => {
results.push(data);
if (results.length % 1000 === 0) {
console.log(`Parsed ${results.length} records from ${filePath}...`);
}
})
.on('end', () => {
const duration = ((Date.now() - startTime) / 1000).toFixed(2);
console.log(`Finished parsing CSV file: ${filePath}. Total records: ${results.length}. Time taken: ${duration}s`);
resolve(results);
})
.on('error', (error: any) => {
console.error(`Error parsing CSV file ${filePath}:`, error);
reject(error);
});
});
}
function generateParityReport(
sentralData: any[],
proserveData: any[],
mappings: Mapping[],
recordIdMapping: [string, string][],
sentralIdColumn: string,
proserveIdColumn: string
): { report: ParityReportEntry[], summary: any } {
console.log('Starting parity report generation...');
const report: ParityReportEntry[] = [];
let totalRecords = 0;
let failedCount = 0;
let passedCount = 0;
let totalMismatches = 0;
const sentralMap = new Map(sentralData.map((row) => [row[sentralIdColumn], row]));
const proserveMap = new Map(proserveData.map((row) => [row[proserveIdColumn], row]));
let skipped = 0;
const totalMappings = recordIdMapping.length;
console.log(`Processing ${totalMappings} record ID mappings...`);
recordIdMapping.forEach(([proserveId, sentralId], index) => {
if (index > 0 && index % 1000 === 0) {
console.log(`Processed ${index} / ${totalMappings} record ID mappings...`);
}
const sentralRow = sentralMap.get(sentralId);
const proserveRow = proserveMap.get(proserveId);
if (!sentralRow || !proserveRow) {
skipped++;
return; // Skip if there's no corresponding row in either dataset
}
totalRecords++;
let recordHasMismatch = false;
mappings.forEach((mapping) => {
let sentralValue = sentralRow[mapping.sentralColumn];
let proserveValue = proserveRow[mapping.proserveColumn];
if (typeof sentralValue === 'string') {
sentralValue = sentralValue.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim();
}
if (typeof proserveValue === 'string') {
proserveValue = proserveValue.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim();
}
if ((sentralValue === '' || sentralValue == null) && (proserveValue === '' || proserveValue == null)) {
return;
}
if (sentralValue !== proserveValue) {
report.push({
proserveId,
sentralId,
proserveColumn: mapping.proserveColumn,
sentralColumn: mapping.sentralColumn,
proserveValue: proserveValue || '',
sentralValue: sentralValue || ''
});
recordHasMismatch = true;
totalMismatches++;
}
});
if (recordHasMismatch) {
failedCount++;
} else {
passedCount++;
}
});
console.log(`Parity report generation completed.`);
console.log(`Total Records Processed: ${totalRecords}`);
console.log(`Passed Records: ${passedCount}`);
console.log(`Failed Records: ${failedCount}`);
console.log(`Total Mismatches Found: ${totalMismatches}`);
console.log(`Total Records Skipped (missing data): ${skipped}`);
const summary = {
totalRecords,
passedCount,
failedCount,
totalMismatches,
skipped
};
return { report, summary };
}
function saveReportToHTML(report: ParityReportEntry[], summary: any, filePath: string): void {
console.log(`Starting to save HTML report to ${filePath}...`);
const fs = require('fs');
// Group report entries by record ID
const groupedReports: { [key: string]: ParityReportEntry[] } = {};
report.forEach(entry => {
const recordId = entry.proserveId || entry.sentralId;
if (!groupedReports[recordId]) {
groupedReports[recordId] = [];
}
groupedReports[recordId].push(entry);
});
// Divide grouped reports into chunks of 1000 entries
const chunks = Object.entries(groupedReports).reduce((result, [recordId, entries], index) => {
const chunkIndex = Math.floor(index / 1000);
if (!result[chunkIndex]) result[chunkIndex] = [];
result[chunkIndex].push([recordId, entries]);
return result;
}, [] as [string, ParityReportEntry[]][][]);
let htmlContent = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Opportunity Object Migration Parity Report</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
h1, h2, h3 { color: #333; }
.summary { margin-bottom: 30px; }
.summary p { font-size: 16px; }
.added, .removed, .modified { margin-bottom: 20px; }
.added-item { color: green; }
.removed-item { color: red; }
table { width: 100%; border-collapse: collapse; margin-bottom: 10px; }
th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
.old-value { background-color: #d4fcdc; }
.new-value { background-color: #fcdcdc; }
.toggle-button {
background-color: #007BFF;
color: white;
padding: 5px 10px;
border: none;
cursor: pointer;
border-radius: 4px;
margin-bottom: 10px;
}
.toggle-button:hover {
background-color: #0056b3;
}
.object-summary, .batch-summary {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #eef;
padding: 10px;
border-radius: 4px;
margin-bottom: 10px;
}
.batch-details {
display: none;
margin-top: 10px;
padding-left: 20px;
}
</style>
<script>
function toggleBatch(id) {
const details = document.getElementById('batch-details-' + id);
const button = document.getElementById('batch-button-' + id);
if (details.style.display === 'none' || details.style.display === '') {
details.style.display = 'block';
button.innerText = 'Collapse Batch';
} else {
details.style.display = 'none';
button.innerText = 'Expand Batch';
}
}
</script>
</head>
<body>
<h1>Opportunity Object Migration Parity Report</h1>
<!-- Overall Summary -->
<div class="summary">
<h2>Overall Summary</h2>
<p><strong>Total Records:</strong> ${summary.totalRecords}</p>
<p><strong>Records with No Mismatches:</strong> ${summary.passedCount}</p>
<p><strong>Records with Mismatches:</strong> ${summary.failedCount}</p>
<p><strong>Total Mismatches:</strong> ${summary.totalMismatches}</p>
<p><strong>Fields Compared per Record:</strong> ${mappings.length}</p>
<p><strong>Total Records Skipped:</strong> ${summary.skipped}</p>
</div>`;
// Generate HTML for each chunk of 1000 records
chunks.forEach((chunk, chunkIndex) => {
htmlContent += `
<div class="modified">
<div class="batch-summary">
<span><strong>Migrated Records - Batch ${chunkIndex + 1}</strong></span>
<button class="toggle-button" id="batch-button-${chunkIndex + 1}" onclick="toggleBatch('${chunkIndex + 1}')">Expand Batch</button>
</div>
<div class="batch-details" id="batch-details-${chunkIndex + 1}">`;
chunk.forEach(([recordId, entries]) => {
const mismatchCount = entries.length;
const proserveId = entries[0].proserveId;
const sentralId = entries[0].sentralId;
htmlContent += `
<div class="object">
<div class="object-summary">
<span><strong>Proserve ID:</strong> ${proserveId} | <strong>Sentral ID:</strong> ${sentralId}</span>
<span><strong>Fields with Mismatches:</strong> ${mismatchCount}</span>
</div>
<div class="object-details">
<h3>Record Level Metrics</h3>
<p>Total Fields with Differences: ${mismatchCount}</p>
<table>
<thead>
<tr>
<th>Proserve Column</th>
<th>Proserve Value</th>
<th>Sentral Column</th>
<th>Sentral Value</th>
</tr>
</thead>
<tbody>`;
entries.forEach(entry => {
htmlContent += `
<tr>
<td>${entry.proserveColumn}</td>
<td class="old-value">${entry.proserveValue || "null"}</td>
<td>${entry.sentralColumn}</td>
<td class="new-value">${entry.sentralValue || "null"}</td>
</tr>`;
});
htmlContent += `
</tbody>
</table>
</div>
</div>`;
});
htmlContent += `
</div>
</div>`;
console.log(`Added Batch ${chunkIndex + 1} with ${chunk.length} records to HTML report.`);
});
htmlContent += `
</body>
</html>`;
fs.writeFileSync(filePath, htmlContent);
console.log(`HTML report successfully saved to ${filePath}`);
}
async function checkParity() {
console.log('Starting parity check process...');
try {
const sentralFilePath = '/Users/svvemur/workspaces/AWSCRMTestAutomation/src/AWSCRMTestAutomation/SentralMerged.csv';
const proserveFilePath = '/Users/svvemur/Downloads/ProserveQueriesAndData/ProserveMerged.csv';
const sentralIdColumn = 'Id';
const proserveIdColumn = 'Id';
const fieldMappingsPath = "/Users/svvemur/workspaces/AWSCRMTestAutomation/src/AWSCRMTestAutomation/TO-BE Data model - Opportunity.csv";
const recordIdMappingPath = '/Users/svvemur/workspaces/AWSCRMTestAutomation/src/AWSCRMTestAutomation/output.csv';
console.log('Reading record ID mappings...');
const recordIdMapping = await readFirstTwoColumns(recordIdMappingPath);
console.log(`Loaded ${recordIdMapping.length} record ID mappings.`);
console.log('Parsing Sentral CSV data...');
const sentralData = await parseCSV(sentralFilePath);
console.log('Parsing Proserve CSV data...');
const proserveData = await parseCSV(proserveFilePath);
console.log('Generating field mappings...');
const mappings: Mapping[] = await generateFieldMappings(fieldMappingsPath);
console.log(`Generated ${mappings.length} field mappings.`);
console.log('Generating parity report...');
const { report, summary } = generateParityReport(sentralData, proserveData, mappings, recordIdMapping, sentralIdColumn, proserveIdColumn);
if (report.length === 0) {
console.log("Data is in parity, no mismatches found.");
} else {
console.log("Data parity discrepancies detected. Generating HTML report...");
const reportFilePath = './parity_report.html';
saveReportToHTML(report, summary, reportFilePath);
console.log("HTML report generation completed.");
console.log(`Total mismatches: ${summary.totalMismatches}`);
}
console.log('Parity check process completed successfully.');
} catch (error) {
console.error("Error processing files:", error);
}
}
function generateFieldMappings(filePath: string): Promise<Mapping[]> {
console.log(`Generating field mappings from file: ${filePath}`);
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(`Error reading field mappings file ${filePath}:`, err);
return reject(err);
}
const mappings: Mapping[] = [];
const lines = data.split('\n');
const headers = lines[0].split(',');
const fieldNameIndex = headers.indexOf('Field Name');
const fieldReplacedIndex = headers.indexOf('Field Replaced from ProServe instance');
if (fieldNameIndex === -1 || fieldReplacedIndex === -1) {
const errorMsg = 'Required columns not found in field mappings CSV file.';
console.error(errorMsg);
return reject(new Error(errorMsg));
}
for (let i = 1; i < lines.length; i++) {
const columns = lines[i].split(',');
if (columns[fieldReplacedIndex]) {
mappings.push({
sentralColumn: columns[fieldNameIndex].trim(),
proserveColumn: columns[fieldReplacedIndex].trim()
});
}
if (i % 1000 === 0) {
console.log(`Processed ${i} lines for field mappings...`);
}
}
console.log(`Completed generating field mappings. Total mappings: ${mappings.length}`);
resolve(mappings);
});
});
}
async function readFirstTwoColumns(filePath: string): Promise<[string, string][]> {
console.log(`Reading first two columns from file: ${filePath}`);
return new Promise<[string, string][]>((resolve, reject) => {
const results: [string, string][] = [];
const readStream = fs.createReadStream(filePath, { encoding: 'utf8' });
readStream.on('error', (err) => {
console.error(`Error reading the file ${filePath}:`, err.message);
reject(`Error reading the file: ${err.message}`);
});
const parser = csv()
.on('headers', (headers: string[]) => {
if (headers.length < 2) {
const errorMsg = 'CSV does not contain at least two columns.';
console.error(errorMsg);
parser.destroy(new Error(errorMsg));
}
console.log(`CSV headers: ${headers.slice(0, 2).join(', ')}`);
})
.on('data', (row: any) => {
try {
const keys = Object.keys(row);
if (keys.length < 2) {
return;
}
const col1 = row[keys[0]].trim();
const col2 = row[keys[1]].trim();
results.push([col1, col2]);
if (results.length % 1000 === 0) {
console.log(`Read ${results.length} record ID mappings...`);
}
} catch (err) {
console.error(`Error processing a row:`, err);
}
})
.on('end', () => {
console.log(`Finished reading record ID mappings. Total mappings: ${results.length}`);
resolve(results);
})
.on('error', (err: Error) => {
console.error(`Error processing the CSV ${filePath}:`, err.message);
reject(`Error processing the CSV: ${err.message}`);
});
readStream.pipe(parser);
});
}
export default checkParity;
Overview of the Added Logs
-
Parsing CSV Files (parseCSV Function)
- Logs when parsing starts and ends for each CSV file.
- Provides periodic updates every 1,000 records to indicate progress.
-
Generating Parity Report (generateParityReport Function)
- Logs the start and completion of the report generation.
- Provides updates every 1,000 record ID mappings processed.
- Summarizes the total records processed, passed, failed, mismatches, and skipped.
-
Saving HTML Report (saveReportToHTML Function)
- Logs the start and successful completion of saving the HTML report.
- Logs each batch added to the HTML report for traceability.
-
Orchestrating the Process (checkParity Function)
- Logs the start and end of the overall parity check process.
- Logs each major step: reading mappings, parsing CSVs, generating mappings, generating reports.
- Logs the outcome based on whether mismatches are found.
-
Generating Field Mappings (generateFieldMappings Function)
- Logs the start and completion of generating field mappings.
- Provides periodic updates every 1,000 lines processed.
-
Reading Record ID Mappings (readFirstTwoColumns Function)
- Logs the start and completion of reading record ID mappings.
- Provides periodic updates every 1,000 mappings read.
- Logs CSV headers for verification.
Tips for Enhanced Logging
-
Use Logging Libraries: For more advanced logging features like log levels (info, warn, error), timestamps, and log file outputs, consider using libraries such as Winston or Bunyan.
-
Handle Large Outputs Carefully: If processing extremely large files, ensure that logging does not become a performance bottleneck. You might want to adjust the frequency of logs or implement conditional logging based on environment variables.
-
Error Logging: All error logs are prefixed with context-specific messages to make debugging easier.
-
Progress Indicators: For very long-running processes, integrating progress bars using packages like cli-progress can provide a more visual and continuous sense of progress.
Final Remarks
With these logging statements in place, you'll have a clearer view of the execution flow and be better equipped to monitor the progress and troubleshoot any issues that arise during the parity check process.