Money + Faction Balance Display

Money Value display with labels next to values, including Faction Balance

// ==UserScript==
// @name         Money + Faction Balance Display
// @namespace    Madwolf
// @version      2.5
// @description  Money Value display with labels next to values, including Faction Balance
// @author       MadWolf [376657]
// @license      MadWolf [376657]
// @grant        GM_addStyle
// @include      https://www.torn.com/*
// @exclude      https://www.torn.com/war.php?step=rankreport&rankID=*
// @noframes
// ==/UserScript==

(function() {
    'use strict';

    // Stop script if we are on excluded pages
    if (
        location.href.includes('/war.php?step=rankreport&rankID=') ||
        location.href.includes('/page.php?sid=points')
    ) {
        console.log('Skipping: on excluded page.');
        return;
    }

    const formatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        maximumFractionDigits: 0
    });

    // Get API key from localStorage or prompt user to enter it
    let apiKey = localStorage.getItem('tornApiKey');
    if (!apiKey) {
        apiKey = prompt('Please enter your Torn API key:');
        if (apiKey && apiKey.trim().length > 0) {
            localStorage.setItem('tornApiKey', apiKey.trim());
        } else {
            console.error('No API key provided, script will not run.');
            return;
        }
    }

    // First AJAX call: get user money info
    $.ajax({
        url: 'https://api.torn.com/user',
        data: {
            selections: 'money',
            key: apiKey
        },
        success: function (data) {
            if (data.error) {
                console.error("API Error: " + data.error.error);
                alert("API Error: " + data.error.error + "\nPlease update your API key.");
                localStorage.removeItem('tornApiKey'); // Clear bad key
                return;
            }

            // Second AJAX call: get faction balance info
            $.ajax({
                url: 'https://api.torn.com/v2/user/factionbalance',
                headers: {
                    'Authorization': 'ApiKey ' + apiKey,
                    'accept': 'application/json'
                },
                success: function(factionData) {
                    if (factionData.error) {
                        console.error("Faction API Error: " + factionData.error.error);
                        // Still show money info even if faction call fails
                    }

                    // Compose HTML
                    let moneyBlocks = '';
                    if (data.vault_amount) {
                        moneyBlocks += `
                            <div class="money-block">
                                <span class="label">Vault:</span>
                                <span class="value">${formatter.format(data.vault_amount)}</span>
                            </div>`;
                    }
                    if (data.cayman_bank) {
                        moneyBlocks += `
                            <div class="money-block">
                                <span class="label">Cayman:</span>
                                <span class="value">${formatter.format(data.cayman_bank)}</span>
                            </div>`;
                    }
                    if (data.company_funds) {
                        moneyBlocks += `
                            <div class="money-block">
                                <span class="label">Company:</span>
                                <span class="value">${formatter.format(data.company_funds)}</span>
                            </div>`;
                    }

                    if (factionData.factionBalance) {
                        moneyBlocks += `
                            <div class="money-block">
                                <span class="label">Faction:</span>
                                <span class="value">${formatter.format(factionData.factionBalance.money)}</span>
                            </div>`;
                    }

                    var resultsDiv = $(`
                        <div class="tmJsonMashupResults">
                            ${moneyBlocks}
                        </div>
                    `);

                    var target = $('div[class^=points]');
                    if (target.length) {
                        // Skip if target is inside or next to excluded elements, or already has our results
                        if (
                            target.closest('.points___oPscQ').length || target.hasClass('points___oPscQ') ||
                            target.closest('.tmJsonMashupResults').length || target.hasClass('tmJsonMashupResults') ||
                            target.find('.tmJsonMashupResults').length
                        ) {
                            console.log('Skipping adding results inside excluded blocks or already injected.');
                            return;
                        }
                        target.append(resultsDiv);
                    } else {
                        console.error("TM script => Target node (.points) not found.");
                    }
                },
                error: function() {
                    console.log('Error fetching faction balance data.');
                }
            });
        },
        error: function () {
            console.log('There was an error fetching money data.');
        }
    });

    // CSS styling
    GM_addStyle(`
    .tmJsonMashupResults {
        display: block;
        margin-top: 4px;
        margin-left: -6px;
        padding: 2px 6px ;
        font-size: 8.9pt;
        background: rgba(0, 0, 0, 0.3);
        border: 1px double rgba(128, 128, 128, 0);
        border-radius: 6px;
        min-width: 150px;
    }
    .tmJsonMashupResults .money-block {
        margin-bottom: 2px;
        white-space: nowrap;
    }
    .tmJsonMashupResults .label {
        font-weight: bold;
        color: white;
        margin-right: 4px;
    }
    .tmJsonMashupResults .value {
        color: #6cc644;
    }
    `);
})();