kalpdev.1 / Sideline reduction tool

// ==UserScript==
// @name         Sideline reduction tool
// @version      1.0
// @description  Checks if the ASIN is already in Qbuzz in return the status as an alert (Answered/Pending))
// @match        https://argus.aka.amazon.com
// @grant        GM_addStyle
//@require https://cdn.jsdelivr.net/npm/sweetalert2@10    
// @license MIT
// @updateURL https://openuserjs.org/meta/kalpdev.1/Sideline_reduction_tool.meta.js
// @downloadURL https://openuserjs.org/install/kalpdev.1/Sideline_reduction_tool.user.js
// ==/UserScript==


GM_addStyle(`
.new-sideline-button {
  background-color: #00796b;
  border: none;
  color: white;
  padding: 2px 2px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 12px;
  position: absolute;
  right: 15px;
}




.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 10; /* Sit on top */
  padding-top: 15%; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
  position: relative;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  border: 1px solid #888;
  width: 35%;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
  -webkit-animation-name: animatetop;
  -webkit-animation-duration: 0.4s;
  animation-name: animatetop;
  animation-duration: 0.4s
}

/* Add Animation */
@-webkit-keyframes animatetop {
  from {top:-300px; opacity:0}
  to {top:0; opacity:1}
}

@keyframes animatetop {
  from {top:-300px; opacity:0}
  to {top:0; opacity:1}
}

/* The Close Button */
.close {
  color: white;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

.modal-header {
  padding: 2px 16px;
  background-color: #00796b;
  color: white;

}

.title {
  text-align: center;
  font-size: 2.5rem
}

.modal-body {
  padding: 2px 16px;
  text-align: center;
}

.modal-footer {
  padding: 2px 16px;
  background-color: #ffffff;
  text-align: center;
}





.radio {
  display: inline-flex;
  overflow: hidden;
  border-radius: 5px;
  box-shadow: 0 0 5px rgb(0,0,0.25);
}
.radio__input {
  display: none;
}

.radio__label {
  padding: 8px 14px;
  font-size: 14px;
  font-family: sans-serif;
  color: #ffffff;
  background: #009578;
  cursor: pointer;
  transition: background 0.1s;
}

.radio__label:not(:last-of-type) {
  border-right: 1px solid #006B56;
}

.radio__input:checked + .radio__label {
  background: #006B56;
}

.hideDefault {
  display: none;
}

.myButtons {
  color: #009578;
  border: 2px solid #009578;
  margin: 10px;
  background: #FFFFFF;
  font-size: 14px;
  padding: 10px 20px;
  border-radius: 10px;
  transition-duration: 0.5s;
  box-shadow: 0 0 5px rgb(0,0,0.10);
  font-weight: bold;

}

.myButtons:hover {
  background-color: #009578;
  color: white;
  font-weight: bold;
  box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);

}


`);


(function () {
    ('use strict')
    const argusSessionStorage = window.sessionStorage // start Chrome session storage
    var startTime = 0
    var endTime = 0


    //****************************************** */
    // check if page is loaded and clear the sessionstyorage
    window.onbeforeunload = function () {
        sessionStorage.setItem("origin", window.location.href);
    }
    //Then in the onload event:

    window.onload = function () {
        if (window.location.href == sessionStorage.getItem("origin")) {
            sessionStorage.clear();
        }
    }
    //****************************************** */

    function checkIfAsinInQbuzz() {
        const asin = document.querySelector('#workItemContainer > span') // get the ASIN location
        if (!asin) {
            // if no ASIN location is found

        } else if (argusSessionStorage.getItem('PreviousASIN') === asin.innerText) {
            // IF ASIN location found, check Chrome session storage for the ASIN and compare with current ASIN. IF the same, exit and go to the end of the if statment --> then repeat the function again after 1 second

        } else {
            startTime = performance.now()
            // if the ASIN in storage is not the same as the current ASIN (The ASIN has changed --> Excute the whole code once)

            sidelinePopup()

            console.log('Checking Qbuzz')
            argusSessionStorage.clear() // clear the current storage
            const ASIN = asin.innerText.toString() // get the ASIN inner text in variable
            argusSessionStorage.setItem('PreviousASIN', ASIN) // write the new ASIN to the storage

            const data = {
                ASIN
            }; // put the asin in json object

            const options = {
                headers: {
                    // create the post request header with the data we want to post
                    'Content-Type': 'application/json'
                },
                method: 'POST',
                body: JSON.stringify(data)
            }

            //fetch('https://tareq.corp.amazon.com:5050', options) // send the request to the server with json
            fetch('https://tareq.corp.amazon.com/qbuzz-db', options)
                .then(response => response.json()) // wait for the response promise and then parse the retruned response to JSON
                .then(data => {
                    if (data.ASIN == ASIN) {
                        swal.fire( {icon: 'info', confirmButtonText: 'Sideline &nbsp;<i class="fa fa-arrow-right"></i>', confirmButtonColor: "#004949",
                            html:`<div>ASIN <b>${ASIN}</b> is already in <b>Qbuzz Tool-</b></div>

<div>User ID: ${data.user_id}<div>
<div>Sideline Date: ${data.Sideline_Date} UTC</div>
<div>Sideline Time: ${data.Sideline_Time} UTC </div>

`

                                   })
                    }

                })
                .catch(function (error) {
                    console.log("Error from App Server - try to restart the browser. If this does not fix the issue contact alsabert");
                    console.log(error);
                    return
                });
        }
        window.setTimeout(checkIfAsinInQbuzz, 1000) // run the above funtion every 1 second (and start the main loop)
    }

    checkIfAsinInQbuzz() // run the function  // this is the first to run //! EBANLE LATER


    //*********************************************************************************************************************************************************/
    //*********************************************************************************************************************************************************/
    //*********************************************************************************************************************************************************/


    function sidelinePopup() {
        const sidelineButton = document.querySelector('#dtSearch > div.sideline-asin-container > sideline-work-item > button') // get the sideline button
        if (!sidelineButton) { // if no button found
        } else {
            sidelineButton.style.display = "none"

            const newBtn = document.createElement("BUTTON");
            newBtn.className = "new-sideline-button";
            newBtn.innerHTML = "Sideline &rarr;";
            const asinLocation = document.querySelector('#workItemContainer')
            asinLocation.appendChild(newBtn);

            const popupWindow = document.createElement('div');
            const popupDiv = `
        <div id="myModal" class="modal">
          <div class="modal-content">

            <div class="modal-header">
            <span class="close">&times;</span>
            <h2 class="title">Please select the reason for sidelining this ASIN</h2>
            </div>

            <div class="modal-body">
                <form id="slform">
                    <div class="radio">
                        <input class="radio__input" type="radio" value="Qbuzz" name="sideline_reason" id="myRadio1">
                        <label class="radio__label" for="myRadio1">Qbuzz</label>
                        </input>

                        <input class="radio__input" type="radio" value="Already in Qbuzz" name="sideline_reason" id="myRadio2">
                        <label class="radio__label" for="myRadio2">Already in Qbuzz</label>
                        </input>

                        <input class="radio__input" type="radio" value="EAR" name="sideline_reason" id="myRadio3">
                        <label class="radio__label" for="myRadio3">EAR</label>
                        </input>

                        <input class="radio__input" type="radio" value="Technical Issue" name="sideline_reason" id="myRadio4">
                        <label class="radio__label" for="myRadio4">Technical Issue</label>
                        </input>

                        <input class="radio__input" type="radio" value="Other" name="sideline_reason" id="myRadio5" checked="checked">
                        <label class="radio__label" for="myRadio5">Other</label>
                        </input>
                    </div>

                    <div id="freetext" class="hideDefault">
                        <textarea type="text" name="sideline_reason_other" id="sideline_reason_other" maxlength="200" cols="50" rows="7" placeholder="Please explain the reason for sidelining \n(max 200 characters)"></textarea>
                    </div>

                    <div class="modal-footer">
                        <button class = "myButtons" id="cancelButton" type="button">Cancel</button>
                        <button class = "myButtons" id="submitButton" type="ubmit">Submit</button>
                    </div>
                  </form>
            </div>
          </div>
        </div>
          `
            popupWindow.innerHTML = popupDiv
            document.body.appendChild(popupWindow);

            // Get the modal
            const modal = document.getElementById("myModal");

            // Get the <span> element that closes the modal
            const span = document.getElementsByClassName("close")[0];

            // When the user clicks the button, open the modal
            newBtn.onclick = function () {
                modal.style.display = "block";
            }


            //#######################################################################################################
            //########################################Radio butoons control##########################################
            function hideFreeText() {
                document.getElementById('freetext').style.display = 'none';
                document.getElementById("sideline_reason_other").required = false
            }

            function showFreeText() {
                document.getElementById('freetext').style.display = 'block';
                document.getElementById("sideline_reason_other").required = true
            }

            const radio1 = document.getElementById('myRadio1');
            radio1.addEventListener("click", hideFreeText, false);

            const radio2 = document.getElementById('myRadio2');
            radio2.addEventListener("click", hideFreeText, false);

            const radio3 = document.getElementById('myRadio3');
            radio3.addEventListener("click", hideFreeText, false);

            const radio4 = document.getElementById('myRadio4');
            radio4.addEventListener("click", hideFreeText, false);

            const radio5 = document.getElementById('myRadio5');
            radio5.addEventListener("click", showFreeText, false);

            //#######################################################################################################
            //##########################################Submit & cancel buttons control##############################


            function handleSubmit(event) {
                console.log('Writing to Maria DB')
                event.preventDefault();
                const dataToSubmit = new Object();
                const formData = new FormData(this);
                dataToSubmit.currentASIN = document.querySelector('#workItemContainer > span').innerText
                dataToSubmit.userID = document.querySelector("#argus-spoof > div > img").getAttribute("alt")
                dataToSubmit.sidelineReason = formData.get('sideline_reason');
                dataToSubmit.sidelineReasonOther = formData.get('sideline_reason_other');

                endTime = performance.now()
                dataToSubmit.timeSpentBeforeSidelining = ((endTime - startTime) / 1000).toFixed(1);

                sendSidlineDataToServer(dataToSubmit)
                document.querySelector("#slform").reset();
                modal.style.display = "none";
                popupWindow.remove();
                sidelineButton.click()

                const finalconfirm = setInterval(function () {
                    const slButton = document.querySelector("body > div.sweet-alert.showSweetAlert.visible > div.sa-button-container > div > button")
                    if (slButton) {
                        slButton.click();
                        clearInterval(finalconfirm);
                    }
                }, 100);

                return
            }

            // function to write the data to mariadb
            function sendSidlineDataToServer(data) {
                const options = {
                    headers: {
                        // create the post request header with the data we want to post
                        'Content-Type': 'application/json'
                    },
                    method: 'POST',
                    body: JSON.stringify(data)
                }

                //fetch('https://tareq.corp.amazon.com:5050', options) // send the request to the server with json
                fetch('https://tareq.corp.amazon.com/maria-db', options)
                    .then(response => response.end()) // wait for the response promise and then parse the retruned response to JSON
                    .catch(function (error) {
                        console.log("error sending sideline data to database");
                        console.log(error);
                        return
                    });
            }


            const form = document.querySelector("#slform"); // select the form
            form.addEventListener('submit', handleSubmit);


            cancelBtn = document.getElementById('cancelButton');
            cancelBtn.onclick = function () {
                modal.style.display = "none";
                document.querySelector("#slform").reset();
            }

            // #######################################################################################################
            //##########################################closing model##############################


            // When the user clicks on <span> (x), close the modal
            span.onclick = function () {
                modal.style.display = "none";
                document.querySelector("#slform").reset();
            }

            // When the user clicks anywhere outside of the modal, close it
            window.onclick = function (event) {
                if (event.target == modal) {
                    modal.style.display = "none";
                    document.querySelector("#slform").reset();
                }
            }

            return

        }

        window.setTimeout(sidelinePopup, 1000)
    }


})()