UNPKG

docparse-supplier-nge

Version:

process ngrid electric utility bill data for use in the docparse system

111 lines (105 loc) 2.76 kB
var num = require('num'); var inspect = require('eyespect').inspector(); var rk = require('required-keys'); module.exports = function (data, cb) { var keys = ['text', 'costSupply']; var err = rk.truthySync(data, keys); if (err) { return cb(err); } var text = data.text; var costSupply = data.costSupply; var lines = text.split(/\r?\n/); var line, totalLine; var pattern = new RegExp(costSupply); var costSupplyFound = false; var totalPattern = /Total\s+Supply/; var costOtherLines = []; for (var i in lines) { line = lines[i].trim(); if (totalPattern.test(line)) { totalLine = line; break; } if (pattern.test(line)) { costSupplyFound = true; continue; } if (!costSupplyFound) { continue; } costOtherLines.push(line); } if (!totalLine) { return cb('total supply charges line not found'); } var costTotal = parseCostTotal(totalLine); if (costTotal === null || costTotal === undefined) { return cb('error getting comp supply cost total'); } var costOther = parseCostOtherLines(costOtherLines); if (!costOther) { return cb('error getting comp supply other costs'); } var checkData = { costOther: costOther, costSupply: costSupply, costTotal: costTotal }; return check(checkData, cb); }; /** * costOther.total + costSupply === costTotal */ function check(data, cb) { var costTotal = data.costTotal; var calc = num(data.costOther.total).add(data.costSupply); var eql = calc.eq(costTotal); if (eql) { return cb(null, data); } var diff = calc.sub(costTotal).toString(); inspect(calc.toString(),'comp supply calculated value'); inspect(costTotal, 'comp supply printed value'); var absDiff = Math.abs(diff); if (absDiff < 0.5) { return cb(null, data); } cb('error getting comp supply cost other, printed value does not match calculated value to within 0.5', data); } function parseCostTotal(line) { var data = processLine(line); var value = data.value; return value; } function processLine(text) { text = text.trim(); var pattern = /(.*?)(-?\d+\.?\d+)\s*$/; var matches = text.match(pattern); if (!matches || matches.length !== 3) { return null; } var description = matches[1].trim(); description = description.replace(/\s{2,}/, ' '); var value = matches[2]; var output = { description: description, value: value }; return output; } function parseCostOtherLines(lines) { var costs = []; var total = num(0); for (var i in lines) { var line = lines[i]; var cost = processLine(line); if (!cost) { continue; } costs.push(cost); total = total.add(cost.value); } return { total: total.toString(), costs: costs }; }