pwner77x / TORN: Item Value

// ==UserScript==
// @name         TORN: Item Value
// @version      2.0.1
// @author       DeKleineKobini
// @description  Show the value for your items.
// @namespace    dekleinekobini.itemvalue
// @require      https://openuserjs.org/src/libs/DeKleineKobini/DKK_Torn_Utilities.js
// @match        https://www.torn.com/item.php
// @license      MIT
// @connect      api.torn.com
// @grant        GM_xmlhttpRequest
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==

setDebug(false);

/* --------------------
CODE - EDIT ON OWN RISK
-------------------- */
requireAPI();
setPrefixEasy("IV");

var apiItems = {};

getCache("tornapi_items").then(response => {
    if (response) {
        debug("Loaded items from the cache!");
        apiItems = response;
    } else {
        sendAPIRequest("torn", null, "items").then(function(response) {
            debug("Loaded items from the api!");
            if (response.items) apiItems = response.items;

            setCache("tornapi_items", response.items, getMillisUntilNewDay());
        });
    }
});

observeMutations(document, ".last-row", true, loadData, { childList: true, subtree: true });

xhrIntercept(function(page, json, uri){
    if(page != "item" || !json) return;

    setTimeout(loadData, 100);
});

function loadData() {
    var total = 0;

    var list = $("ul[aria-hidden=false]");
    list.find("li[data-category]").each(function (index) {
        var id = $(this).attr("data-item");
        var wrap = $(this).find(".name-wrap");

        var value = apiItems[id].market_value;
        var amount = $(this).find(".qty").eq(0).html() || 1;

        if (value > 0) {
             wrap.not(".itemValue").append("(Value: " + formatCurrency(value) + " each  . Total <span class='id-" + id + "'></span>)");
            wrap.addClass("itemValue");
        }

        $(".id-" + id).html(formatCurrency(value * amount));
        total += amount * value;
    });

    list.not(".total").prepend("<li>Total Value <span class='totalValue'></span></li>");
    list.addClass("total");
    $(".totalValue").html(formatCurrency(total));
}

function formatCurrency(value, decimals, currency) {
    if (!decimals) decimals = 0;
    if (!currency) currency = "$";

    return currency + value.format(decimals);
}