@returns {string|null} - Permit type.
*/
function getPermitType(permitNumber) {
if (permitNumber.includes('EL')) {
return 'Electrical';
} else if (permitNumber.includes('SL')) {
return 'Solar';
} else {
return null;
}
}
/**
Get solar date from permits data.
@param {Array} permits - Array of permit objects.
@returns {string|null} - Solar date.
*/
function getSolarDate(permits) {
for (const permit of permits) {
if (permit.type === 'Solar') {
return permit.issueDate;
}
}
return null;
}
/**
Check for an increase in energy usage after solar permit issue date.
@param {Array} permits - Array of permit objects.
@param {string} solarDate - Solar permit issue date.
@returns {Object} - Object indicating increase and old panels status.
*/
function checkIncreaseInEnergyUsage(permits, solarDate) {
const increase = permits.some(permit => {
const description = permit.description.toLowerCase();
const keywords = ["air conditioner", "a/c", "hvac", "pool", "spa"];
const issueDate = new Date(permit.issueDate);
code
return keywords.some(keyword => description.includes(keyword)) && issueDate > new Date(solarDate);
});
const oldPanels = new Date(solarDate) < new Date('2015-01-01');
return { increase, oldPanels };
}
/**
Extract data from a row in the table.
@param {Cheerio} row - Row element.
@returns {string} - Extracted data.
*/
function getDataFromRow(row) {
const cells = row.find('div');
const data = cells.eq(1);
return data.text().trim();
}
/**
Format date string to 'MM / DD / YYYY' format.
@param {string} dateStr - Date string.
@returns {string} - Formatted date string.
*/
function formatDate(dateStr) {
const date = new Date(dateStr);
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const year = date.getFullYear();
return ${month} / ${day} / ${year};
}
module.exports = {
getParcelData
};
Here's an improved version with some fixes and better error-handling, formatting, and ensuring proper data extraction from the HTML:
javascript
const axios = require('axios');
const cheerio = require('cheerio');
const https = require('https');
// Configure HTTPS agent to disable certificate validation (not recommended for production)
const agent = new https.Agent({
rejectUnauthorized: false
});
/**
* Fetch parcel data from the given URL.
* @param {string} url - The URL to fetch data from.
* @returns {Object} - Parcel data.
*/
async function getParcelData(url) {
try {
const response = await axios.get(url, { httpsAgent: agent });
const html = response.data;
const $ = cheerio.load(html);
const parcel = {};
// Parse parcel information
parseParcelInformation($, parcel);
// Parse permits data
parcel.permits = parsePermitsData($);
// Additional data processing
parcel.solarDate = getSolarDate(parcel.permits);
parcel.trueup = checkIncreaseInEnergyUsage(parcel.permits, parcel.solarDate);
console.log(parcel);
return parcel;
} catch (error) {
console.error('Error fetching data:', error);
throw error; // Re-throw the error to handle it elsewhere if needed
}
}
/**
* Parse parcel information from the Cheerio instance.
* @param {CheerioStatic} $ - Cheerio instance.
* @param {Object} parcel - Parcel object to populate.
*/
function parseParcelInformation($, parcel) {
const parcelInfoTable = $('#j_id0\\:parcelInformation\\:j_id166\\:0\\:j_id167');
const rows = parcelInfoTable.find('.row');
if (rows.length < 4) {
throw new Error("Unexpected number of rows in parcel information table.");
}
const address = getDataFromRow($(rows[0]));
const addressMatches = address.match(/^(.*?)(?:\s+)(DR|ST|LN|PL|AVE|CIR|BLVD|WAY|WY|ROAD|RD)(.*?)(\d+)$/im);
if (addressMatches) {
const [, street, streetType, city, zip] = addressMatches;
parcel.street = `${street.trim()} ${streetType.trim()}`;
parcel.city = city.trim();
parcel.zip = zip.trim();
} else {
console.error("Invalid street address format.");
parcel.street = "Unknown";
parcel.city = "Unknown";
parcel.zip = "Unknown";
}
parcel.number = getDataFromRow($(rows[1])).trim();
const coordinates = getDataFromRow($(rows[3])).split('/');
if (coordinates.length === 2) {
parcel.coordinates = { latitude: coordinates[0].trim(), longitude: coordinates[1].trim() };
} else {
parcel.coordinates = { latitude: "Unknown", longitude: "Unknown" };
}
}
/**
* Parse permits data from the Cheerio instance.
* @param {CheerioStatic} $ - Cheerio instance.
* @returns {Array} - Array of permit objects.
*/
function parsePermitsData($) {
const permits = [];
$('#permitDataTable tr').each((index, row) => {
if (index > 0) {
const cells = $(row).find('td');
if (cells.length >= 6) {
const permit = {
number: cells.eq(0).text().trim(),
link: cells.eq(0).find('a').attr('href'),
status: cells.eq(1).text().trim(),
description: cells.eq(2).text().trim(),
issueDate: formatDate(cells.eq(3).text().trim()),
type: getPermitType(cells.eq(0).text().trim()),
expirationDate: formatDate(cells.eq(5).text().trim())
};
permits.push(permit);
}
}
});
return permits;
}
/**
* Get permit type based on permit number.
* @param {string} permitNumber - Permit number.
* @returns {string|null} - Permit type.
*/
function getPermitType(permitNumber) {
if (permitNumber.includes('EL')) {
return 'Electrical';
} else if (permitNumber.includes('SL')) {
return 'Solar';
} else {
return null;
}
}
/**
* Get solar date from permits data.
* @param {Array} permits - Array of permit objects.
* @returns {string|null} - Solar date.
*/
function getSolarDate(permits) {
for (const permit of permits) {
if (permit.type === 'Solar') {
return permit.issueDate;
}
}
return null;
}
/**
* Check for an increase in energy usage after solar permit issue date.
* @param {Array} permits - Array of permit objects.
* @param {string} solarDate - Solar permit issue date.
* @returns {Object} - Object indicating increase and old panels status.
*/
function checkIncreaseInEnergyUsage(permits, solarDate) {
if (!solarDate) {
return { increase: false, oldPanels: false };
}
const increase = permits.some(permit => {
const description = permit.description.toLowerCase();
const keywords = ["air conditioner", "a/c", "hvac", "pool", "spa"];
const issueDate = new Date(permit.issueDate);
return keywords.some(keyword => description.includes(keyword)) && issueDate > new Date(solarDate);
});
const oldPanels = new Date(solarDate) < new Date('2015-01-01');
return { increase, oldPanels };
}
/**
* Extract data from a row in the table.
* @param {Cheerio} row - Row element.
* @returns {string} - Extracted data.
*/
function getDataFromRow(row) {
const cells = row.find('div');
if (cells.length < 2) {
return "Unknown";
}
return cells.eq(1).text().trim();
}
/**
* Format date string to 'MM/DD/YYYY' format.
* @param {string} dateStr - Date string.
* @returns {string} - Formatted date string or original if invalid.
*/
function formatDate(dateStr) {
const date = new Date(dateStr);
if (isNaN(date.getTime())) {
return dateStr; // Return original string if invalid
}
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const year = date.getFullYear();
return `${month}/${day}/${year}`;
}
module.exports = {
getParcelData
};
Explanation of Fixes:
Error Handling: Ensured rows in parseParcelInformation has the expected number of rows and handled invalid coordinates gracefully.
Validation: Added validation for cell count in parsePermitsData before accessing cells to avoid errors.
Date Formatting: Improved formatDate to handle invalid dates by returning the original string if the date conversion fails.
General Improvements: Incorporated better logging for invalid street address format and improved error messaging throughout the script.
Note:
Security Tip: Disabling certificate validation (rejectUnauthorized: false) is dangerous for production as it can expose security vulnerabilities such as MITM attacks. Always ensure certificate validation in a production environment.