Skip to content

Instantly share code, notes, and snippets.

@hlfbt
Created October 14, 2018 00:48
Show Gist options
  • Save hlfbt/2204437101355f22e491d539d25b4380 to your computer and use it in GitHub Desktop.
Save hlfbt/2204437101355f22e491d539d25b4380 to your computer and use it in GitHub Desktop.
Does a tally of amount spent, orders and items ordered on amazon. To be executed on any amazon order history page.
function fetchPage(link, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', link);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200)
callback.call(xhr, xhr);
};
xhr.send();
}
function makeDoc(docString) {
var doc = document.implementation.createHTMLDocument();
doc.documentElement.innerHTML = docString;
return doc;
}
function walkYears(years, callback, result) {
if (typeof result == 'undefined')
result = {
'years': {},
'items': 0,
'orders': 0,
'total': 0
};
if (years.length > 0) {
var year = years.pop(0);
var link = '/gp/your-account/order-history?opt=ab&digitalOrders=1&unifiedOrders=1&orderFilter=year-' + year;
console.log("Now fetching year " + year + "...");
fetchPage(link, function (xhr) {
var page = makeDoc(xhr.response);
var pages = [];
[].forEach.call(
page.querySelectorAll('.a-pagination .a-normal a'),
function (a) {
pages.push(a.getAttribute('href'));
}
);
walkPages(pages, function (total, items, orders) {
result.years[year] = this;
result.total += total;
result.items += items;
result.orders += orders;
walkYears(years, callback, result);
}, getPageTotal(page), getPageItems(page), getTotalOrders(page));
});
} else {
callback.call(result, result);
}
}
function walkPages(pages, callback, total = 0, items = 0, orders = undefined) {
if (pages.length > 0) {
var page = pages.pop(0);
fetchPage(page, function (xhr) {
var doc = makeDoc(xhr.response);
total += getPageTotal(doc);
items += getPageItems(doc);
if (typeof orders === 'undefined') orders = getTotalOrders(doc);
walkPages(pages, callback, total, items, orders);
});
} else {
callback.call({'total': total, 'items': items, 'orders': orders}, total, items, orders);
}
}
function getPageTotal(page) {
var total = 0;
[].forEach.call(
page.querySelectorAll('.a-color-price'),
function (a) {
total += +(a.textContent.replace(',', '.').replace(/^[^\d]+/, ''));
}
);
return total;
}
function getPageItems(page) {
return page.querySelectorAll('.a-color-price').length;
}
function getTotalOrders(page) {
return +(page.querySelector('span.num-orders').textContent.replace(/^(\d+).*/, '$1'));
}
var years = [];
[].forEach.call(
document.querySelectorAll('[id^=\'orderFilterEntry-year\']'),
function (a) {
years.push(a.getAttribute('value').match(/year-(\d{4})/)[1]);
}
);
walkYears(years, function (result) {
window.prices = result;
console.log(result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment