Kuroi_mato_O / Sel.be QOL

// ==UserScript==
// @name         Sel.be QOL
// @namespace    http://tampermonkey.net/
// @version      0.1.7
// @description  Различные твики для операторов, по вопросам и предложениям пишите в телеграм
// @author       Kuroi_Mato_O
// @supportURL   http://t.me/kuroi_mato_O
// @updateURL    https://openuserjs.org/meta/Kuroi_mato_O/Sel.be_QOL.meta.js
// @downloadURL  https://openuserjs.org/install/Kuroi_mato_O/Sel.be_QOL.user.js
// @copyright    2021, Kuroi_mato_O (https://openuserjs.org/users/Kuroi_mato_O)
// @license      MIT
// @include      https://zakupay.sel-be.ru/core/offers/operator/workplace
// @include      /^https:\/\/zakupay.sel-be\.ru\/core\/offers\/\d*\/?$
// @include      /^https:\/\/zakupay.sel-be\.ru\/core\/files\/scan\/\d*\/download/
// @require      https://code.jquery.com/jquery-3.4.1.min.js
// @require      https://code.jquery.com/ui/1.12.1/jquery-ui.min.js
// @require      https://raw.githubusercontent.com/uzairfarooq/arrive/master/minified/arrive.min.js
// @icon         https://www.google.com/s2/favicons?domain=sel-be.ru
// @grant        none

// ==/UserScript==

(function() {
    'use strict';




    //ID BUTTON TEXT AND COLOR REPLACE
var checkExistOprBtn = setInterval(function() {
   if ($('.operator-btn').length) {
       let shit = document.querySelector('.operator-btn');
       let piss = document.querySelector('.manage-panel span[class^="label"]');
       let orderID = document.querySelector('.upper-spread-buttons > a:nth-child(1)');
       shit.innerText = piss.innerText.replace(/\s+/g, '') + ' (#' + orderID.outerHTML.replace(/\D+/g, '') + ')';
       console.log("Shit= " + shit);
       console.log("Piss= " + piss);
   if (parseFloat(shit.innerText) <= 100){
       shit.style.cssText = 'background: linear-gradient(90deg, rgba(70,226,140,1) 0%, rgba(5,255,0,1) 100%);'
   }
   else if (parseFloat(shit.innerText) > 100 && parseFloat(shit.innerText) <= 400){
       shit.style.cssText = 'background: linear-gradient(90deg, rgba(70,226,140,1) 0%, rgba(255,184,0,1) 100%);'
   }
   else{
       shit.style.cssText = 'background: linear-gradient(90deg, rgba(70,226,140,1) 0%, rgba(255,8,0,1) 100%);'
   };
      clearInterval(checkExistOprBtn);
   }

}, 100);
// check every 100ms
    //COPY ID TO CLIPBOARD
//     document.arrive(".operator-btn", function(){

//     });

    // var checkExistOprBtn2 = setInterval(function() {
     document.arrive(".operator-btn", function(){
   if ($('.operator-btn').length) {
       let shit = document.querySelector('.operator-btn');
       let orderID = document.querySelector('.upper-spread-buttons > a:nth-child(1)').outerHTML.replace(/\D+/g, '');
       shit.addEventListener("contextmenu", copyOrderID);
       let TextCopiedBtn = document.createElement('div');
       TextCopiedBtn.innerHTML = "ID скопирован :3";
       TextCopiedBtn.setAttribute('id', 'TextCopiedButton');
       let operatorBtn = document.querySelector('.operator-btn');
       operatorBtn.after(TextCopiedBtn);


       function copyOrderID() {
            const cb = navigator.clipboard;
            cb.writeText(orderID);
           $(TextCopiedBtn).fadeIn(1000).animate({ "top": "+=40px" }, {duration: "slow", queue: false} ).fadeOut(5000).animate({ "top": "-=40px" }, "fast" );

}
   }
     });
//        clearInterval(checkExistOprBtn);
//  }
//
// }, 100);
    //DIAMETER BUTTON
var checkExistDiamBtn = setInterval(function() {
    if ($('#FormatTab > ul > li:nth-child(3)').length){
        var diameterButton = document.createElement('button');
        diameterButton.setAttribute('id', 'diameterBtn');
        diameterButton.textContent = 'Ø';
        document.querySelector("#FormatTab > ul > li:nth-child(3)").insertAdjacentElement('afterEnd', diameterButton);

      clearInterval(checkExistDiamBtn);
   }

}, 100);
var checkExistDiamBtn2 = setInterval(function() {
    if ($('#diameterBtn').length){
        function copyText() {
            const cb = navigator.clipboard;
            const DiamBtn = document.querySelector('#diameterBtn');
            cb.writeText(DiamBtn.innerText);
}
clearInterval(checkExistDiamBtn);
document.querySelector('#diameterBtn').addEventListener('click', copyText);
}

}, 100);


    //SETTINGS BUTTON
var checkExistPartSaveBtn = setInterval(function() {
        if ($('#part-draft-btn').length){
        var settingsButton = document.createElement('button');
        settingsButton.setAttribute('id', 'settings');
        settingsButton.setAttribute('class', 'settingsMenu');
        document.querySelector('#part-draft-btn').insertAdjacentElement('afterEnd', settingsButton);
        $('.settingsMenu').append('<ul class="settingsList hidden">');
        $('.settingsList').append('<li><div class="toggle-btn"><input type="checkbox" class="cb-value" /><span class="round-btn"></span></div> Сырная</li>');
        $('.settingsList').append('<li><div class="toggle-btn"><input type="checkbox" class="cb-value" /><span class="round-btn"></span></div> Жёппа</li>');
        $('.settingsList').append('<li><div class="toggle-btn"><input type="checkbox" class="cb-value" /><span class="round-btn"></span></div> Уууух!</li>');
      clearInterval(checkExistPartSaveBtn);
   }
}, 100);
var checkExistSettingsBtn = setInterval(function() {
        if ($('#settings').length){
            $('#settings').on('click', function(){
                $('.settingsList').toggleClass('hidden');
            }).on('click', '.settingsList', function(e) {
    // clicked on descendant div
    e.stopPropagation();
});
//
      clearInterval(checkExistSettingsBtn);
   }
}, 100);

    //checkbox
    var checkExistCheckBoxes = setInterval(function() {
        if ($('.toggle-btn').length){
    $('.cb-value').click(function() {
  var mainParent = $(this).parent('.toggle-btn');
  if($(mainParent).find('input.cb-value').is(':checked')) {
    $(mainParent).addClass('active');
  } else {
    $(mainParent).removeClass('active');
  }

});
        clearInterval(checkExistCheckBoxes);
   }
}, 100);


    //INN BUTTONS not working???
var checkExistInnWindow = setInterval(function(){
    if ($('.modal-content').length){
        console.log('modal-content.length = true');
        if ($('#s2id_list-combo-ajax').length){
            var innButton1 = document.createElement('button');
            innButton1.setAttribute('id', 'petrovichBtn');
            innButton1.textContent = 'Петрович';
            document.querySelector(".modal-header").insertAdjacentElement('afterEnd', innButton1);
    } else { console.log('кнопка ИНН не вставилась');}

    }
    clearInterval(checkExistInnWindow);
}, 100);



    //PREVIEW WINDOW & BUTTON [BROKEN]
/*var checkExistPreviewBtn = setInterval(function() {
    if ($('.scan-group:last-child').length){
        var prvBtn = document.querySelector('.scan-group:last-child');
        var prvText = document.querySelector('.scan-group:last-child label');
        var prvWndCont = document.querySelector('.scan-dialog-class');
        var prvWndChld = document.querySelector('#scan-dialog');
        function hideShit(){
            prvWndCont.style.cssText = 'visibility: hidden;';
            prvText.style.cssText = 'visibility: hidden;';
            console.log('else');
            prvBtn.style.cssText = 'visibility: visible; position: fixed; right: 1px; bottom: 15px;';
            console.log(prvBtn + ' prevbtn1');
        }
        hideShit()
        $('.scan-group:last-child').on('contextmenu', function (event) {
            var keycode = ( event.keyCode ? event.keyCode : event.which );
            if (keycode === 3) {
               if ($(prvWndCont).css('visibility') == 'hidden'){
               prvText.style.cssText = 'visibility: visible!important;';
               prvWndCont.style.cssText = 'visibility: visible; width: 500px; height: 500px; left:150px; top: 50px;';
               $(prvWndCont).resizable();
               $(prvWndCont).draggable({ scroll: false });
               $('.zoom').draggable();
               $('.zoom').resizable();
               prvWndChld.style.cssText = 'width: 486px; height: 468px;';

                   console.log(prvBtn + ' if');
               prvBtn.style.cssText = 'visibility: visible; position: relative; right: 5px; bottom: 0;';
               console.log('if');
                } else {
                    hideShit()
                    //prvWndCont.style.cssText = 'visibility: hidden;';
                    //prvText.style.cssText = 'visibility: hidden;';
                    //console.log('else');
                    //prvBtn.style.cssText = 'visibility: visible; position: fixed; right: 1px; bottom: 15px;';
                    //console.log(prvBtn + ' else');
                }
    }
});
$(function(){
var sPositions = localStorage.positions,
    positions = JSON.parse(sPositions);
$.each(positions, function (id, pos) {
    $("." + id).css(pos)
})

$(".scan-dialog-class").draggable({
    containment: "body",
    scroll: false,
    stop: function (event, ui) {
        positions[this.id] = ui.position
        localStorage.positions = JSON.stringify(positions)
    }
});
});


      clearInterval(checkExistPreviewBtn);
   }

}, 100);
*/
    //FILE NAME SHORTENER
function truncateMiddle(word) {
    const tooLongChars = 40; // arbitrary

    if (word.length < tooLongChars) {
        return word;
    }

    const ellipsis = '...';
    const charsOnEitherSide = Math.floor(tooLongChars / 2) - ellipsis.length;

    return word.slice(0, charsOnEitherSide) + ellipsis + word.slice(-charsOnEitherSide);
}

var checkExistFileName = setInterval(function() {
    if ($('.name.ng-binding').length) {
        var fileName = document.querySelector('.name.ng-binding');
        fileName.innerText = truncateMiddle(fileName.innerText);
        console.log(fileName.innerText + ' ssanina kakaya to');
        clearInterval(checkExistFileName);}
}, 1000);
// check every 1000ms

//ZOOMING PREVIEW [BROKEN]
/*
if (/^https:\/\/zakupay.sel-be\.ru\/core\/files\/scan\/\d*\/download/.test (location.href)) {
// DRAGGABLE IMAGE        $('img').draggable({ cursor: 'move',helper : 'original'});
    console.log('prev-img-detected');
    var govnina = setInterval(function() {
        if ($('img').length) {
            $('img').wrap("<div class='new'></div>" );
            $(document).ready(function (){
            var scroll_zoom = new ScrollZoom($('body'),8,0.5)

})

function ScrollZoom(container,max_scale,factor){
	var target = container.children().first()
	var size = {w:target.width(),h:target.height()}
	var pos = {x:0,y:0}
	var zoom_target = {x:0,y:0}
	var zoom_point = {x:0,y:0}
	var scale = 1
	target.css('transform-origin','0 0')
	target.on("mousewheel DOMMouseScroll",scrolled)

	function scrolled(e){
    if (e.shiftKey) {
		var offset = container.offset()
		zoom_point.x = e.pageX - offset.left
		zoom_point.y = e.pageY - offset.top

		e.preventDefault();
		var delta = e.delta || e.originalEvent.wheelDelta;
		if (delta === undefined) {
	      //we are on firefox
	      delta = e.originalEvent.detail;
	    }
	    delta = Math.max(-1,Math.min(1,delta)) // cap the delta to [-1,1] for cross browser consistency

	    // determine the point on where the slide is zoomed in
	    zoom_target.x = (zoom_point.x - pos.x)/scale
	    zoom_target.y = (zoom_point.y - pos.y)/scale

	    // apply zoom
	    scale += delta*factor * scale
	    scale = Math.max(1,Math.min(max_scale,scale))

	    // calculate x and y based on zoom
	    pos.x = -zoom_target.x * scale + zoom_point.x
	    pos.y = -zoom_target.y * scale + zoom_point.y


	    // Make sure the slide stays in its container area when zooming out
	    if(pos.x>0)
	        pos.x = 0
	    if(pos.x+size.w*scale<size.w)
	    	pos.x = -size.w*(scale-1)
	    if(pos.y>0)
	        pos.y = 0
	     if(pos.y+size.h*scale<size.h)
	    	pos.y = -size.h*(scale-1)

	    update()
	}

	function update(){
		target.css('transform','translate('+(pos.x)+'px,'+(pos.y)+'px) scale('+scale+','+scale+')')
	}
}
}
        clearInterval(govnina);}

}, 1000);

}
*/
    //CTRL+F SEARCH (W/O ENTER)
    const debounce = (fn, ms = 0) => {
        let timeoutId;
        return function(...args) {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => fn.apply(this, args), ms);
        };
    };


    document.querySelector('#search-input').addEventListener("keydown", debounce(() => {
        document.querySelector('span[func="search"]').click();
        document.querySelector('#search-input').focus();
        window.GcSpread.Sheets.FocusHelper.setActiveElement(null);
    }, 600));

    window.addEventListener("keydown", function(e) {
        if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
            e.preventDefault();
            window.GcSpread.Sheets.FocusHelper.setActiveElement(null);
            document.querySelector('#search-input').focus();
            document.querySelector('#search-input').select();


        }
    })


})();