All files parser.js

96.46% Statements 109/113
85.96% Branches 49/57
96.55% Functions 28/29
97.25% Lines 106/109
1 2 3 4 5 6 7 8 9 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295  2x 2x 2x 2x   2x   2x 2x             24x   21x 21x 21x                             460x 460x 460x     460x 97x         460x       460x                     675x 675x 301x   675x                     37x 37x 37x 10x   27x                           336x   336x 335x 335x   253x   253x 237x       335x                       1x 1x 1x             13x 13x 13x 12x 7x 7x 6x 6x 6x     6x 6x         21x 21x 21x 21x 386x     21x 3x     18x         1x 1x   1x 1x 1x 3x 3x   1x                           8x 8x 8x   8x 4x     4x 4x 16x 16x                   4x   16x   16x   4x 4x         7x       7x   7x   7x 6x 16x 6x 316x 6x 6x 6x     6x   1x                       4x 4x 4x   4x 27x 15x 12x         12x 12x         4x 3x   1x           4x     2x                            
// Dependencies
const Promise = require('bluebird');
const cheerio = require('cheerio');
const moment = require('moment-timezone');
const debug = require('debug')('node-cba-netbank');
 
moment.tz.setDefault('Australia/Sydney');
 
const submittableSelector = 'input,select,textarea,keygen';
const rCRLF = /\r?\n/g;
 
//  Utilities
//  reference: https://github.com/cheeriojs/cheerio/blob/master/lib/api/forms.js
//  Add support for allow `disabled` and `button` input element in the serialized array.
function serializeArray(element, options = { disabled: false, button: false }) {
  // Resolve all form elements from either forms or collections of form elements
  return element
    .map((i, elem) => {
      const $elem = cheerio(elem);
      Eif (elem.name === 'form') {
        return $elem.find(submittableSelector).toArray();
      }
      return $elem.filter(submittableSelector).toArray();
    })
    .filter(
      // Verify elements have a name (`attr.name`)
      // and are not disabled (`:disabled`) if `options.disabled === false`
      // and cannot be clicked (`[type=submit]`) if `options.button === true`
      // are used in 'x-www-form-urlencoded' ('[type=file]')
      `[name!=""]${options.disabled ? '' : ':not(:disabled)'}:not(${options.button ? '' : ':submit, :button, '}:image, :reset, :file)` +
        // and are either checked/don't have a checkable state
        ':matches([checked], :not(:checkbox, :radio))',
      // Convert each of the elements to its value(s)
    )
    .map((i, elem) => {
      const $elem = cheerio(elem);
      const name = $elem.attr('name');
      let value = $elem.val();
 
      // If there is no value set (e.g. `undefined`, `null`), then default value to empty
      if (value == null) {
        value = $elem.attr('type') === 'checkbox' ? 'on' : '';
      }
 
      // If we have an array of values (e.g. `<select multiple>`),
      // return an array of key/value pairs
      Iif (Array.isArray(value)) {
        return value.map(val => ({ name, value: val.replace(rCRLF, '\r\n') })); //   These can occur inside of `<textarea>'s` // to guarantee consistency across platforms // We trim replace any line endings (e.g. `\r` or `\r\n` with `\r\n`)
        // Otherwise (e.g. `<input type="text">`, return only one key/value pair
      }
      return { name, value: value.replace(rCRLF, '\r\n') };
 
      // Convert our result to an array
    })
    .get();
}
 
//  parse the balance to a double number.
//  e.g. '$1,766.50 CR', '$123.00 DR'
//  Positive is CR, and negative is DR.
function parseCurrencyText(text) {
  let amount = Number(text.replace(/[^0-9.]+/g, ''));
  if (text.indexOf('DR') > -1) {
    amount = -amount;
  }
  return amount;
}
 
//  Parse:
// <div class="FieldElement FieldElementLabel FieldElementNoLabel">
//   <span class="CurrencySymbol CurrencyLabel PreFieldText">$</span>
//   <span title="$" class="Currency field WithPostFieldText">1,767.44</span>
//   <span class="PostFieldText">CR</span>
// </div>
//  to Number `1767.44`.
function parseCurrencyHtml(elem) {
  const e = cheerio.load(`<div>${elem}</div>`);
  const currency = parseFloat(e('.Currency').text().replace(/,/g, '').trim());
  if (e('.PostFieldText').text().trim() === 'DR') {
    return -currency;
  }
  return currency;
}
 
// Transaction format
// {
//  timestamp,
//  date,
//  description,
//  amount,
//  balance,
//  trancode,
//  receiptnumber
// }
function parseTransaction(json) {
  try {
    //  try parse the date from 'Date.Sort[1]' first
    const dateTag = json.Date.Sort[1];
    let t = moment.utc(dateTag, 'YYYYMMDDHHmmssSSS').tz('Australia/Sydney');
    if (!t.isValid()) {
      //  try parse the date from 'Date.Text' if previous attempt failed
      t = moment(json.Date.Text, 'DD MMM YYYY');
      //  use sort order to distinguish different transactions.
      if (dateTag && !isNaN(+dateTag)) {
        t.millisecond(+dateTag);
      }
    }
 
    return {
      timestamp: t.valueOf(),
      date: t.format(),
      //  replace newline with '; '
      description: json.Description.Text.replace(/\n/g, '; '),
      amount: parseCurrencyText(json.Amount.Text),
      balance: parseCurrencyText(json.Balance.Text),
      trancode: json.TranCode.Text || '',
      receiptnumber: json.ReceiptNumber.Text || '',
    };
  } catch (err) {
    //  ignore the error for the misformatted transaction, and return null.
    debug(err);
    debug(`Cannot parse the given transaction: ${JSON.stringify(json)}`);
    return null;
  }
}
 
// Parsers
 
function parseTitle(resp) {
  return new Promise((resolve) => {
    const $ = cheerio.load(resp.body);
    const contentType = resp.headers['content-type'];
    if (contentType && contentType.indexOf('text/html') >= 0) {
      const m = /NetBank - ([^-]+)/.exec($('title').text());
      if (m) {
        const title = m[1].trim();
        debug(`parseTitle(): found title => '${title}'`);
        return resolve(Object.assign({}, resp, { title }));
      }
    }
    debug('parseTitle(): cannot find title');
    return resolve(resp);
  });
}
 
function parseForm(resp) {
  return new Promise((resolve, reject) => {
    const $ = cheerio.load(resp.body);
    const form = {};
    serializeArray($('form'), { disabled: true, button: true }).forEach((item) => {
      form[item.name] = item.value;
    });
 
    if (Object.keys(form).length === 0) {
      return reject('parseForm(): Cannot find form.');
    }
 
    return resolve(Object.assign({}, resp, { form: Object.assign({}, resp.form, form) }));
  });
}
 
function parseViewState(resp) {
  return new Promise((resolve) => {
    const form = Object.assign({}, resp.form);
    //  get new view state of asp.net
    const REGEX_VIEW_STATE = /(__VIEWSTATE|__EVENTVALIDATION|__VIEWSTATEGENERATOR)\|([^|]+)\|/g;
    let match = REGEX_VIEW_STATE.exec(resp.body);
    while (match) {
      form[match[1]] = match[2];
      match = REGEX_VIEW_STATE.exec(resp.body);
    }
    return resolve(Object.assign({}, resp, { form: Object.assign({}, resp.form, form) }));
  });
}
 
//  Account format:
// {
//  name,
//  link,
//  bsb,
//  account,
//  number: {bsb+account}
//  balance
// }
function parseAccountList(resp) {
  return new Promise((resolve, reject) => {
    const $ = cheerio.load(resp.body);
    const accountRows = $('.main_group_account_row');
 
    if (!accountRows || accountRows.length === 0) {
      return reject('Cannot find account list.');
    }
 
    let accounts = [];
    accountRows.each((index, elem) => {
      const $$ = cheerio.load(elem);
      accounts.push({
        name: $$('.NicknameField .left a').text().trim(),
        link: $$('.NicknameField .left a').attr('href'),
        bsb: $$('.BSBField .text').text().replace(/\s+/g, '').trim(),
        account: $$('.AccountNumberField .text').text().replace(/\s+/g, '').trim(),
        balance: parseCurrencyHtml($$('.AccountBalanceField')),
        available: parseCurrencyHtml($$('.AvailableFundsField')),
      });
    });
 
    accounts = accounts
      //  Assemble the `bsb` and `account` to construct `number`
      .map(acc => Object.assign({}, acc, { number: `${acc.bsb}${acc.account}` }))
      //  validate the account info
      .filter(acc => acc.name && acc.link && acc.account);
 
    debug(`parseAccountList(): found ${accounts.length} accounts`);
    return resolve(Object.assign({}, resp, { accounts }));
  });
}
 
function parseHomePage(resp) {
  return parseForm(resp).then(parseTitle).then(parseAccountList);
}
 
function parseTransactions(resp) {
  return new Promise((resolve, reject) => {
    //  Get transactions
    const m = /({"Transactions":(?:[^;]+))\);/.exec(resp.body);
    let transactions;
    if (m) {
      const json = JSON.parse(m[1]);
      const pendings = json.OutstandingAuthorizations.map(parseTransaction).filter(v => !!v);
      debug(`parseTransactions(): found ${pendings.length} pending transactions`);
      transactions = json.Transactions.map(parseTransaction).filter(v => !!v);
      debug(`parseTransactions(): found ${transactions.length} transactions`);
      debug(`parseTransactions(): There ${json.More ? 'are ' : 'is NO '}more transactions.`);
      Iif (json.Limit) {
        debug('parseTransactions(): However, it reaches the limit.');
      }
      return resolve(Object.assign({}, resp, { transactions, more: json.More, limit: json.Limit, pendings }));
    }
    return reject('Cannot find transactions in the resp');
  });
}
 
//  Parse the account list from TransactionHistory/History.aspx page
// AccountWithKeys
// {
//  name,
//  number,
//  key
// }
function parseAccountListWithKeys(resp) {
  return new Promise((resolve, reject) => {
    const $ = cheerio.load(resp.body);
    const accounts = [];
 
    $('#ctl00_ContentHeaderPlaceHolder_updatePanelAccount').find('option').each((i, e) => {
      const texts = $(e).text().split('|').map(t => t.trim());
      if (texts.length === 2) {
        const acc = {
          name: texts[0],
          number: texts[1].replace(/\s+/g, ''),
          key: $(e).attr('value'),
        };
        Eif (acc.key && acc.number && acc.name) {
          accounts.push(acc);
        }
      }
    });
 
    if (accounts.length > 0) {
      resolve(Object.assign({}, resp, { accounts }));
    } else {
      reject('Cannot find accounts keys');
    }
  });
}
 
function parseTransactionPage(resp) {
  return parseForm(resp).then(parseTitle).then(parseTransactions).then(parseAccountListWithKeys);
}
 
module.exports = {
  serializeArray,
  parseTitle,
  parseForm,
  parseViewState,
  parseAccountList,
  parseHomePage,
  parseCurrencyText,
  parseCurrencyHtml,
  parseTransaction,
  parseTransactions,
  parseAccountListWithKeys,
  parseTransactionPage,
};