// ==UserScript==
// @name Aliexpress Order info getter track
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Получение информации из заказа и трека
// @author Andronio
// @match https://trade.aliexpress.ru/orderList.htm*
// @match https://trade.aliexpress.ru/order_list.htm*
// @match https://trade.aliexpress.com/orderList.htm*
// @match https://trade.aliexpress.com/order_list.htm*
// @noframes
// ==/UserScript==
/*
prodName - Название товара
picURL - URL-ссылка на картинку-превью товара
prodPrice - Цена товара
today - Сегодняшняя дата
orderNum - Номер заказа
\t - Табуляция, переход к следующей ячейке
picPrefix - 1 - добавлять префик picURL= для адреса картинки, 0 - не добавлять
track - Трек-номер заказа
date - Дата автозакрытия заказа
Строка должна начинаться и заканчиваться символом обратной кавычки
*/
var orderStr = `prodName + '\t' + picURL + '\t' + prodPrice + '\t' + today + '\t' + orderNum`;
var trackStr = `track + '\t' + date`;
let picPrefix = 1;
/*
Далее не трогать
*/
let ordersMass = [];
let trackMass = [];
(function () {
'use strict';
// Рисуем окно с кнопками
var div = document.createElement('div');
div.className = 'mybox';
let product = document.querySelectorAll('.order-item-wraper');
let hasTrackable = false;
if (product.length == 0) {
div.innerHTML = '<p class="noorders">Нет заказов</p>';
} else {
let str = document.body.innerHTML.split("var appealInfoParams = encodeURIComponent('")[1].split("');")[0];
if (str.match(/\[(\{("\w+":["\w]+,)+"\w+":["\w]+\},){0,30}\{("\w+":["\w]+,)+"\w+":["\w]+\}\]/g)) {
ordersMass = eval(str);
ordersMass.forEach(order => {
if (order.orderStatus == "WAIT_BUYER_ACCEPT_GOODS") {
hasTrackable = true;
}
});
}
div.innerHTML = `<button class="infoGetter" myattr="-1">Все заказы</button>`;
if (hasTrackable) div.innerHTML +=`<button class="trackGetter" myattr="99" disabled>Треки</button>`;
for (let i = 0; i < product.length; i++) {
let productName = product[i].querySelectorAll(".product-title > a.baobei-name")[0].getAttribute("title").substr(0,20);
div.innerHTML += `<br><button class="infoGetter" myattr="${i}">${i+1} - <span style="color:green">${productName}</span></button>`;
if (hasTrackable && ordersMass[i].orderStatus == 'WAIT_BUYER_ACCEPT_GOODS')
div.innerHTML += `<button class="trackGetter" myattr="${i+100}" disabled>Трек</button>`;
}
}
document.body.append(div);
var styles = `
.mybox {
position: fixed;
top: 0;
right: 0;
background: white;
box-shadow: 1px -1px 4px 1px;
max-width: 40%;
max-height: 400px;
padding: 10px 10px;
overflow-y: auto;
overflow-x: hidden;
z-index:9999;
}
.noorders {
color: red;
text-align: center;
font-size: 1.5em;
padding: 5px;
margin: 0;
}
.infoGetter {
display: inline;
margin-right:auto;
margin-top: 2px;
cursor:pointer;
padding: 5px;
width: 180px;
text-align: left;
}
.trackGetter {
display: inline;
margin-right:auto;
margin-top: 2px;
cursor:pointer;
padding: 5px;
width: 46px;
text-align: left;
}
.greenbutton{
background-color: LightGreen;
}`
var styleSheet = document.createElement("style")
styleSheet.type = "text/css"
styleSheet.innerText = styles
document.head.append(styleSheet)
div.addEventListener('click', buttonClick);
if (hasTrackable) getTracks();
})();
function buttonClick(event) {
let elem = event.target;
if (elem.tagName != "BUTTON") {
elem = elem.parentNode;
if (elem.tagName != "BUTTON") return;
}
let orderString;
let num = +elem.getAttribute('myattr');
if (num > 98) return trackBuff(num, elem);
else {
let product = document.querySelectorAll('.order-item-wraper');
let productPrice = document.querySelectorAll(".amount-num");
let orderNumber = document.querySelectorAll(".order-info > .first-row > span.info-body");
let today = formatDate();
let prodName, prodPrice, orderNum;
if (num > -1) {
// один заказ
let productName = product[num].querySelectorAll(".product-title > a.baobei-name");
let picURL = product[num].querySelectorAll(".pic.s50 > img")[0].src;
if (picPrefix) picURL = "picURL=" + picURL;
prodName = `=ГИПЕРССЫЛКА("https:\/\/www.aliexpress.ru\/item\/${productName[0].getAttribute("productid")}.html";` +
`"${productName[0].getAttribute("title").substr(0,80)}")`;
prodPrice = productPrice[num].innerText.match(/\d+\.\d+/);
if (prodPrice)
prodPrice = prodPrice[0].replace(/\./,",");
else
prodPrice = productPrice[num].innerText.trim();
orderNum = orderNumber[num].innerText;
orderString = eval(orderStr);
} else {
// много заказов
orderString = "";
for (let num = 0; num < orderNumber.length; num++) {
let productName = product[num].querySelectorAll(".product-title > a.baobei-name");
let picURL = product[num].querySelectorAll(".pic.s50 > img")[0].src;
if (picPrefix) picURL = "picURL=" + picURL;
prodName = `=ГИПЕРССЫЛКА("https:\/\/www.aliexpress.ru\/item\/${productName[0].getAttribute("productid")}.html";` +
`"${productName[0].getAttribute("title").substr(0,80)}")`;
prodPrice = productPrice[num].innerText.match(/\d+\.\d+/);
if (prodPrice)
prodPrice = prodPrice[0].replace(/\./,",");
else
prodPrice = productPrice[num].innerText.trim();
orderNum = orderNumber[num].innerText;
orderString += eval(orderStr);
orderString += "\r\n";
}
}
}
navigator.clipboard.writeText(orderString).then(function () {
console.log('Async: Copying to clipboard was successful!');
window.mybtn = elem;
window.mybtn.classList.add("greenbutton");
setTimeout(() => window.mybtn.classList.remove("greenbutton"), 500);
}, function (err) {
console.error('Async: Could not copy text: ', err);
});
}
function trackBuff(num, elem){
num -= 100;
let date, track, orderString = "";
let trackMassCopy = trackMass.slice();
if (num > -1) {
let el = trackMassCopy.find(index => index.id == ordersMass[num].id);
date = el.date;
track = el.track;
orderString = eval(trackStr);
} else {
for (let i = 0; i < ordersMass.length; i++) {
if (ordersMass[i].orderStatus == "WAIT_BUYER_ACCEPT_GOODS") {
let el = trackMassCopy.shift();
date = el.date;
track = el.track;
orderString += eval(trackStr);
}
orderString += "\r\n";
}
}
navigator.clipboard.writeText(orderString).then(function () {
console.log('Async: Copying to clipboard was successful!');
window.mybtn = elem;
window.mybtn.classList.add("greenbutton");
setTimeout(() => window.mybtn.classList.remove("greenbutton"), 500);
}, function (err) {
console.error('Async: Could not copy text: ', err);
});
}
function getTracks() {
ordersMass.forEach(order => {
if (order.orderStatus == "WAIT_BUYER_ACCEPT_GOODS") {
trackMass.push({id: order.id, track: "", date: ""});
}
});
let requests = trackMass.map(order => fetch(`${location.protocol}//${location.hostname}/order_detail.htm?orderId=${order.id}`));
Promise.all(requests)
.then(responses => Promise.all(responses.map(r => r.text())))
.then(texts => {
for (let i = 0; i < texts.length; i++) {
let obj = document.createElement('html');
obj.innerHTML = texts[i];
let track = obj.querySelector(".flush-btn").getAttribute("logisticsNo");
let date = obj.querySelector('.order-reminder');
if (!track || !date) return alert("Не получил информацию о заказе");
date = date.innerText.match(/\d{4}-\d\d-\d\d/g);
if (date.length > 0) date = date[0].replace(/\d\d(\d\d)-(\d\d)-(\d\d)/, '$3.$2.$1');
else return alert("Не правильная дата в заказе");
trackMass[i].track = track;
trackMass[i].date = date;
}
document.querySelectorAll(".trackGetter").forEach(elem => elem.removeAttribute("disabled"));
})
.catch(err => alert(`Ошибка ${err}`));
}
function formatDate() {
let date = new Date();
let dd = date.getDate();
if (dd < 10)
dd = '0' + dd;
let mm = date.getMonth() + 1;
if (mm < 10)
mm = '0' + mm;
let yy = date.getFullYear() % 100;
if (yy < 10)
yy = '0' + yy;
return dd + '.' + mm + '.' + yy;
}