Last active
July 3, 2016 21:48
-
-
Save asherkin/efbdbb2ed824028bbc4db631c3f03251 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage: | |
// | |
// HalifaxAPI.getTransactionHistoryQIF(300).then((qif) => console.log(qif)); | |
// | |
(function() { | |
'use strict'; | |
const StatementBaseUrl = 'https://secure.halifax-online.co.uk/personal/link/lp_statement_ajax'; | |
const StatementType = Object.freeze({ | |
Latest: 'latest', | |
Previous: 'previous', | |
Next: 'next', | |
}); | |
function getStatementUrl(type) { | |
const cacheBuster = Date.now(); | |
let url = StatementBaseUrl; | |
url += '?_=' + cacheBuster; | |
url += '&viewstatement=' + type; | |
return url; | |
} | |
function fetchStatement(type) { | |
return fetch(getStatementUrl(type), { | |
credentials: 'include', | |
}).then((response) => { | |
if (!response.ok) { | |
throw new Error('HTTP Error: ' + response.status + ' - ' + response.statusText); | |
} | |
return response.json(); | |
}); | |
} | |
function getTransactions(statement) { | |
return statement.transactions.items; | |
} | |
function getTransactionHistoryInternal(limit, resolve, transactionHistory) { | |
let statementType = StatementType.Previous; | |
if (transactionHistory.length === 0) { | |
statementType = StatementType.Latest; | |
} | |
fetchStatement(statementType) | |
.then(getTransactions) | |
.then((transactions) => { | |
Array.prototype.push.apply(transactionHistory, transactions); | |
if (transactionHistory.length < limit) { | |
getTransactionHistoryInternal(limit, resolve, transactionHistory); | |
} else { | |
resolve(transactionHistory); | |
} | |
}); | |
} | |
function getTransactionHistory(limit) { | |
return new Promise((resolve, reject) => { | |
let transactionHistory = []; | |
getTransactionHistoryInternal(limit, resolve, transactionHistory); | |
}); | |
} | |
function getTransactionHistoryQIF(limit) { | |
return new Promise((resolve, reject) => { | |
getTransactionHistory(limit) | |
.then((transactions) => { | |
resolve('!Type:Bank\n' + transactions.map((transaction) => ({ | |
date: new Date(transaction.date), | |
payee: transaction.completeDescription.join(' ').replace(/\s+/g, ' ').trim(), | |
amount: transaction.amount.amount, | |
})).map((transaction) => [ | |
'D' + transaction.date.getDate() + '/' + (transaction.date.getMonth() + 1) + '/' + transaction.date.getFullYear(), | |
'P' + transaction.payee, | |
'T' + transaction.amount.toFixed(2), | |
'^', | |
].join('\n')).join('\n')); | |
}); | |
}); | |
} | |
window.HalifaxAPI = { | |
getTransactionHistory: getTransactionHistory, | |
getTransactionHistoryQIF: getTransactionHistoryQIF, | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment