velzevur / Reload Teespring

// ==UserScript==
// @name         Reload Teespring
// @namespace    http://your.homepage/
// @version      0.1
// @description  Reload teespring campaigngs page and keep track of the sales
// @author       Velzevur
// @match        teespring.com/dashboard/campaigns
// @grant        none
// ==/UserScript==

// local storage
function read_old_state() {
    if(localStorage.vlzState) {
        return JSON.parse(localStorage.vlzState);
    }
    return {};
}

function write_state(state) {
    localStorage.vlzState = JSON.stringify(state);
}


function read_messages() {
    if(localStorage.vlzMessages) {
        return JSON.parse(localStorage.vlzMessages);
    }
    return {};
}

function write_messages(messages) {
    localStorage.vlzMessages = JSON.stringify(messages);
}
// ==





// scrap state
function current_state() {
    var divs = $('div.list_item');
    var data = {};
    $.each(divs, function(idx, d)
           {
        var dataid= $(d).attr('data-id');
        var name = $(d).children('.list_item__title').children('.campaign__title_link').attr('title');
        var image = $(d).children('.list_item__thumbnail').children('a').children('img').attr('src');
        var campaign_reserved = $(d).children('.list_item__campaign_reserved').children('.campaign_reserved__sold').children('.campaign_reserved').html().split('/');
        var target = parseInt(campaign_reserved.pop());
        var sold = parseInt(campaign_reserved.pop());
        var profit;
        if(sold < 5) {
            profit = 0;
        } else {
            profit = parseInt($(d).children('.list_item__campaign_profit').children('.campaign_profit').html().split('$').pop());
        }
        var time_left = $(d).children('.list_item__campaign_time').children('.campaign_time__status').html().split('d')[0];
        var days_left = 0;
        if(time_left.slice(-1) != 'h') {
            days_left = parseInt(time_left);
        }
        data[dataid] = {'name': name,
                        'image': image,
                        'bought': sold,
                        'target': target,
                        'profit': profit,
                        'remaining_days': days_left};
    });
    return $.extend({}, data);
}

function make_magic_happen() {
    var oldState = read_old_state();
    var currentState = current_state();
    write_state(currentState);
}


// css magic

function draw_message(message) {
    var html = '<div class="message  ' + message.event + '"><span class="list_item__title campaign__title_link"> ';
    html += '<img src="' +  message.imgurl + '" alt="" height="20" width="20" class="rounded"> ';
    html += message.campaign + '</span> ';
    if(message.value) {
        html += " has " + message.event + " " + message.value;
    } else {
        html += " " + message.event;
    }
    html += "</div>";
    return html;
}

function draw_messages(messages){
    $('div.dashboard__content').append('<div id="bubbles"></div>');
    $('#bubbles').css('position', 'absolute');
    $('#bubbles').css('top', '100px');
    $('#bubbles').css('right', '0px');
    var head = "<div>Events:</div>";
    var accum = "";
    $.each(messages, function(idx, msg) {
        accum += draw_message(msg);
    });
    var clearBtn = "<div id='clear'>Clear all messages</div>";
    if(accum ==="") {
        accum = "<div class='italic'>No new messages</div>";
        clearBtn = "";
    }
    $('#bubbles').html(head + accum + clearBtn);
    set_style();
}

function set_style() {
    $('.message').css('padding', '5px');
    $('.message').css('border-radius', '2em');
    $('.message').css('border-style', 'solid');
    $('.message').css('border-width', '1px');
    $('.message').css('font-size', '70%');
    $('.message').css('margin', '10px');


    $('.sold').css('border-color', '#6CBF30');
    $('.sold').css('background-color', '#B6DF98');

    $('.canceled').css('border-color', 'red');


    $('img.rounded').css('border-radius', '5px');

    //$('.ended').css('background', 'repeating-linear-gradient(45deg,transparent, transparent 15px,#fff 10px, #eee 20px)');

    $('#clear').css('cursor','pointer');
    $('.italic').css('font-style','italic');
    $('.italic').css('font-size', '60%');

    $('#bubbles').css('min-width', '200px');

}


// diff states

function make_message(campaignName, img, event, value){
    var msg = {'campaign':campaignName, 'imgurl':img, 'event':event};
    if(value !== undefined){
        msg.value = value;
    }
    return msg;
}

function find_message(campaign, event, allMessages) {
    for(var i =0; i < allMessages.length; i++) {
        if(allMessages[i].campaign == campaign && allMessages[i].event == event) {
            return allMessages[i];
        }
    }
    return undefined;
}

function merge_messages(oldMessages, newMessages) {
    var result = [];
    $.each(oldMessages, function(idx, oldMsg) {
        var newV = find_message(oldMsg.campaign, oldMsg.event, newMessages);
        if(newV) {
            if(newV.value) {
                var v = newV;
                v.value = newV.value + oldMsg.value;
                result.push(v);
            }
        } else { // no change
            result.push(oldMsg);
        }
    });
    $.each(newMessages, function(idx, newMsg) {
        var oldV = find_message(newMsg.campaign, newMsg.event, oldMessages);
        if(!oldV) {
            result.push(newMsg);
        }
    });
    return result;
}

function diff_states(oldState, newState) {
    var newMessages = [];
    $.each(oldState, function(dataid, oldEntry) {
        var name = oldEntry.name;
        var img = oldEntry.image;
        var newEntry = newState[dataid];
        if(newEntry) {
            var diffs = diff_entry(oldEntry, newEntry);
            $.each(diffs, function(event, value) {
                newMessages.push(make_message(name, img, event, value));
            });
        } else { // campaign missing: ended or suspended
            if(oldState.remaining_days === 0) {
                newMessages.push(make_message(name, img, "ended early"));
            } else {
                newMessages.push(make_message(name, img, "ended"));
            }
        }

    });
    return newMessages;
}

function diff_entry(oldE, newE) {
    var cntDiff = newE.bought - oldE.bought;
    var result = {};
    if(cntDiff > 0) {
        result.sold = cntDiff;
    }
    if(cntDiff < 0) {
        result.canceled = cntDiff;
    }
    var oldTipped = oldE.bought >= oldE.target;
    var newTipped = newE.bought >= newE.target;
    if(oldTipped === false && newTipped === true) {
        result.tipped = undefined;
    }
    return result;
}


$( document ).ready(function() {
    var c = current_state();
    var o = read_old_state();
    var newmsgs = diff_states(o, c);
    var oldmsgs = read_messages();
    var allMsgs = merge_messages(oldmsgs, newmsgs);
    write_messages(allMsgs);
    write_state(c);
    draw_messages(allMsgs);
    $("#clear").click(function(){
        write_messages({});
        draw_messages([]);
    });
    setInterval(function(){
        location.reload(true);
    },60 * 1000 ); // 60 seconds
});