Skip to content

Instantly share code, notes, and snippets.

@poldim
Last active August 1, 2021 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poldim/96af32979a838dbb4816bd3352152859 to your computer and use it in GitHub Desktop.
Save poldim/96af32979a838dbb4816bd3352152859 to your computer and use it in GitHub Desktop.
AliExpress Order Detail to CSV Downloader - tampermonkey script
// ==UserScript==
// @name Ali Express Order Downloader
// @namespace https://gist.github.com/
// @version 0.3
// @description Retrieve Aliexpress order information and export as CSV via clipboard
// @author You
// @match https://trade.aliexpress.com/order*ist.htm*
// @grant unsafeWindow
// @grant GM_xmlhttpRequest
// @grant GM_setClipboard
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @require https://code.jquery.com/jquery-latest.js
// @require https://www.17track.net/externalcall.js
// ==/UserScript==
// Original order data script: https://gist.github.com/Bolukan/16146e6e9c3c7e05a8a23f8b2f8a1dc4
// Original order tracking script: https://gist.github.com/rafal83/6dea29d07743a8a7bab091e31e3c9782
// I couldnt get the tracking number and status to extract to the tables.
function parseDate(txt)
{
// 012345678901234567
// 10:31 May. 21 2019
// var d = new Date(year, month (0-11), day, hours, minutes, seconds, milliseconds);
return new Date(txt.slice(14,18),("Jan.Feb.Mar.Apr.May.Jun.Jul.Aug.Sep.Oct.Nov.Dec.".indexOf(txt.slice(6,10)))/4, txt.slice(11,13), txt.slice(0,2), txt.slice(3,5),0,0);
}
var listTrack = new Array();
var totalTrack = 0;
var dt = 0;
getTrackingNumber = function(data){
//console.log(data);
console.log(listTrack.length+'/'+totalTrack);
var orderId = data.cainiaoUrl.split('=')[1];
var trackId = data.tracking[0].mailNo;
var oneUrl = 'https://www.17track.net/fr/track?nums='+trackId;
var status = data.tracking[0].keyDesc;
listTrack.push(trackId);
if(data.tracking[0].traceList) {
dt = new Date(data.tracking[0].traceList[0].eventTime);
status += '<br/>'+dt.toLocaleString()+'<br/>'+data.tracking[0].traceList[0].desc;
}
jQuery('.button-logisticsTracking[orderid='+orderId+']')
.before('<td class="tracking_number" style="background-color: red;color: white;font-weight: bold;padding:0px">'+data.tracking[0].mailNo+'</td>')
.before('<span class="tracking_status" style="color: black;font-weight: bold;font-size: 13px;">'+status+'</span>');
};
(function() {
'use strict';
function getAllTrackingNumber() {
console.log("Search orders");
listTrack.length=0;
totalTrack = jQuery('.button-logisticsTracking').length;
if(totalTrack > 0) {
console.log("Total "+totalTrack);
jQuery('.button-logisticsTracking').each(function() {
var orderId = jQuery(this).attr('orderid');
jQuery.ajax({
url:document.location.protocol+'//ilogisticsaddress.aliexpress.com/ajax_logistics_track.htm?orderId='+orderId+'&callback=getTrackingNumber',
dataType:'jsonp'
});
});
}
}
getAllTrackingNumber();
})();
var orders = [];
var items = [];
var reqs = [];
var options = { weekday: undefined, year: 'numeric',
month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit'};
$(".order-item-wraper").each((ind, eo)=>{
var hasTracking = $(eo).find(".button-logisticsTracking ").length > 0;
let order = {
order_id: $(eo).find(".order-info .first-row .info-body ").text().trim(),
order_time: parseDate($(eo).find(".order-info .second-row .info-body").text().trim()).toLocaleDateString('nl-NL', options),
order_amount: $(eo).find(".order-amount .amount-num").text().trim(),
order_status: $(eo).find(".order-status .f-left").text().trim(),
store_name: $(eo).find(".store-info .first-row .info-body").text().trim(),
store_url: $(eo).find(".store-info .second-row a:first()").attr('href'),
order_tr_num: $(eo).find(".order-action .tracking_number").text().trim(),
order_tr_stat: $(eo).find(".order-body .order-action .tracking_status").text().trim(),
product_action: $(eo).find(".product-action span:first()").text().trim(),
hasTracking: hasTracking,
}
orders.push(order);
// console.log("Tracking number: " + order.order_tr_num );
// console.log("Tracking status: " + order.product_action );
var products = [];
var inum = 0;
$(eo).find(".order-body").each((i,eb)=>{
$(eb).find(".product-sets").each((i,ep)=>{
let product = {
order_product_num: ++inum,
product_id: $(ep).find(".product-title .baobei-name").attr('productId'),
product_title: $(ep).find(".product-title .baobei-name").attr('title'),
product_url: $(ep).find(".product-title .baobei-name").attr('href'),
product_pic_url: $(ep).find(".product-left img").attr('src'),
product_snapshot: $(ep).find(".product-snapshot .baobei-name").attr('href'),
product_count: $(ep).find(".product-amount span:nth-child(2)").text().trim().slice(1), // remove parcer for different currency
product_price: $(ep).find(".product-amount span:first()").text().trim(),
product_skuid: $(ep).find(".product-property span:first() span:first()").attr('id'),
product_property: $(ep).find(".product-property span:first() span:first()").text().trim(),
//product_action: $(ep).find(".product-action span:first()").text().trim(),
order: order,
};
// console.log($(ep).find(".product-action span:first()").text().trim());
products.push(product); // local all products
items.push(product); // global all products
// console.log(item);
});
// console.log(products);
});
/*
let order = {
id: $(el).find(".order-info .first-row .info-body ").text().trim(),
status: $(el).find(".order-status .f-left").text().trim(),
orderPrice: $(el).find(".amount-num").text().trim(),
productPriceAndAmount: $(el).find(".product-right .product-amount").text().trim().replace(/(?:\s\s)/g, ""),
productsNames: products.map((it)=> it.title).join(", "),
orderDate: $(el).find(".order-info .second-row .info-body").text().trim(),
sellerName: $(el).find(".store-info .first-row .info-body").text().trim(),
hasTracking: hasTracking,
products: products,
};
*/
/*
if (hasTracking){
var req = new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: "GET",
url: "https://ilogisticsaddress.aliexpress.com/ajax_logistics_track.htm?orderId=" + order.id + "&callback=test",
onload:(data)=>{
order.tracking = eval(data.responseText).tracking;
order.trackingNumber = order.tracking.map(it=>it.mailNo).join(", ");
resolve(order);
orders.push(order);
},
onerror: () => reject(400)
});
});
reqs.push(req);
} else{
orders.push(order);
}
*/
});
//console.log(JSON.stringify(orders));
$.when.apply(null, reqs).done(function(){
// console.log(orders);
// console.log(orders.length);
});
//<button id="search-btn" class="ui-button ui-button-primary search-btn" type="button">Search</button>
$('#mybutton').one('click', function(){
var r=$('<input/>').attr({
type: "button",
id: "field",
value: 'LOAD CSV'
});
$("body").append(r);
});
$('<button/>', {
text: "Copy Orders CSV",
id: 'csvBtn',
click: function () {
$("#csvBtn").text("Loading...");
Promise.all(reqs).then(o =>{
var s = "";
items.forEach(e=> {
s += e.order.order_id + "\t";
s += e.order.order_time + "\t";
s += ((e.order_product_num==1) ? e.order.order_amount : "") + "\t";
s += e.order.order_status + "\t";
s += e.order.hasTracking + "\t";
// s += e.order.order_tr_num + "\t";
// s += e.order.order_tr_stat + "\t";
s += e.order_product_num + "\t";
s += "\"" + e.product_title + "\"\t";
s += "\"" + e.product_property + "\"\t";
s += e.product_count + "\t";
s += e.product_price + "\t";
s += e.order.product_action + "\t";
s += e.product_id + "\t";
s += ((typeof(e.product_skuid)=='undefined') ? "" : "\"" + e.product_skuid + "\"") + "\t";
s += e.order.store_name + "\t";
s += "https:" + e.order.store_url + "\t";
s += "https:" + e.product_url + "\t";
s += "\"" + e.product_pic_url + "\"\t";
s += "https:" + e.product_snapshot + "\t";
s += "https://trade.aliexpress.com/order_detail.htm?orderId=" + e.order.order_id + "\t";
s += "\n";
});
//console.log(s);
GM_setClipboard (s);
$("#csvBtn").text("Orders on clipboard");
});
}
}).appendTo("#appeal-alert");
$('<button/>', {
text: "Copy HEADER",
id: 'headerBtn',
click: function () {
$("#headerBtn").text("Copied!");
Promise.all(reqs).then(o =>{
var h = "";
{
h += "Order Number" + "\t";
h += "Order Date" + "\t";
h += "Total Order Amount" + "\t";
h += "Order Status" + "\t";
h += "Tracking Available" + "\t";
// h += "Tracking Number" + "\t";
// h += "Tracking Status" + "\t";
h += "Item Number of Order" + "\t";
h += "Item Title" + "\t";
h += "Item Selections" + "\t";
h += "Item QTY" + "\t";
h += "Item Price" + "\t";
h += "Item Actions" + "\t";
h += "Item Number" + "\t";
h += "SKU" + "\t";
h += "Store Name" + "\t";
h += "Store URL" + "\t";
h += "Item URL" + "\t";
h += "Item Picture URL" + "\t";
h += "Item Snapshot URL" + "\t";
h += "Order Detail URL" + "\t";
};
GM_setClipboard (h);
$("#headerBtn").text("Header copied");
});
}
}).appendTo("#appeal-alert");
@kongomongo
Copy link

kongomongo commented May 25, 2021

Heya, how about this (you forgot to wait for the getTrackingNumber call to finish).
I am updating the orders array in getTrackingNumber to fill the tracking fields order_tr_num + order_tr_stat so they will be accessible in export

// ==UserScript==
// @name         Ali Express Order Downloader
// @namespace    https://gist.github.com/
// @version      0.3
// @description  Retrieve Aliexpress order information and export as CSV via clipboard
// @author       You
// @match        https://trade.aliexpress.com/orderList.htm*
// @grant        unsafeWindow
// @grant        GM_xmlhttpRequest
// @grant        GM_setClipboard
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @require      https://code.jquery.com/jquery-latest.js
// @require      https://www.17track.net/externalcall.js
// ==/UserScript==

// Original order data script: https://gist.github.com/Bolukan/16146e6e9c3c7e05a8a23f8b2f8a1dc4
// Original order tracking script: https://gist.github.com/rafal83/6dea29d07743a8a7bab091e31e3c9782

// I couldnt get the tracking number and status to extract to the tables. 

function parseDate(txt)
{
    // 012345678901234567
    // 10:31 May. 21 2019
    // var d = new Date(year, month (0-11), day, hours, minutes, seconds, milliseconds);
    return new Date(txt.slice(14,18),("Jan.Feb.Mar.Apr.May.Jun.Jul.Aug.Sep.Oct.Nov.Dec.".indexOf(txt.slice(6,10)))/4, txt.slice(11,13), txt.slice(0,2), txt.slice(3,5),0,0);
}

var listTrack = new Array();
var totalTrack = 0;
var dt = 0;

getTrackingNumber = function(data){
    //console.log(data);
    console.log(listTrack.length+'/'+totalTrack);
    var orderId = data.cainiaoUrl.split('=')[1];
    var trackId = data.tracking[0].mailNo;
    var oneUrl = 'https://www.17track.net/fr/track?nums='+trackId;
    var status = data.tracking[0].keyDesc;
    listTrack.push(trackId);
    if(data.tracking[0].traceList) {
        dt = new Date(data.tracking[0].traceList[0].eventTime);
        status += '<br/>'+dt.toLocaleString()+'<br/>'+data.tracking[0].traceList[0].desc;
    }
    jQuery('.button-logisticsTracking[orderid='+orderId+']')
        .before('<td class="tracking_number" style="background-color: red;color: white;font-weight: bold;padding:0px">'+data.tracking[0].mailNo+'</td>')
        .before('<span class="tracking_status" style="color: black;font-weight: bold;font-size: 13px;">'+status+'</span>');

    for(var o in orders){
        if(orders[o].order_id == orderId){
            orders[o].order_tr_num = data.tracking[0].mailNo;
            orders[o].order_tr_stat = status;
            break;
        }
    }
};

(function() {
    'use strict';

    function getAllTrackingNumber() {
        console.log("Search orders");
        listTrack.length=0;
        totalTrack = jQuery('.button-logisticsTracking').length;
        if(totalTrack > 0) {
            console.log("Total "+totalTrack);
            jQuery('.button-logisticsTracking').each(function() {
                var orderId = jQuery(this).attr('orderid');
                jQuery.ajax({
                    url:document.location.protocol+'//ilogisticsaddress.aliexpress.com/ajax_logistics_track.htm?orderId='+orderId+'&callback=getTrackingNumber',
                    dataType:'jsonp'
                });
            });
        }
    }
    getAllTrackingNumber();
})();

var orders = [];
var items = [];
var reqs = [];
var options = { weekday: undefined, year: 'numeric',
                month: '2-digit', day: '2-digit',
                hour: '2-digit', minute: '2-digit'};
$(".order-item-wraper").each((ind, eo)=>{
  var hasTracking = $(eo).find(".button-logisticsTracking ").length > 0;
  let order = {
    order_id:     $(eo).find(".order-info .first-row .info-body ").text().trim(),
    order_time:   parseDate($(eo).find(".order-info .second-row .info-body").text().trim()).toLocaleDateString('nl-NL', options),
    order_amount: $(eo).find(".order-amount .amount-num").text().trim(),
    order_status: $(eo).find(".order-status .f-left").text().trim(),
    store_name:   $(eo).find(".store-info .first-row .info-body").text().trim(),
    store_url:    $(eo).find(".store-info .second-row a:first()").attr('href'),
    order_tr_num: $(eo).find(".order-action .tracking_number").text().trim(),
    order_tr_stat: $(eo).find(".order-body .order-action .tracking_status").text().trim(),
    product_action: $(eo).find(".product-action span:first()").text().trim(),
    hasTracking:  hasTracking,
  }
  orders.push(order);
  console.log("Tracking number: " + order.order_tr_num );
  console.log("Tracking status: " + order.product_action );
  console.log("store_url: " + order.store_url );

  var products = [];
  var inum = 0;
  $(eo).find(".order-body").each((i,eb)=>{
    $(eb).find(".product-sets").each((i,ep)=>{
      let product = {
        order_product_num: ++inum,
        product_id:        $(ep).find(".product-title .baobei-name").attr('productId'),
        product_title:     $(ep).find(".product-title .baobei-name").attr('title'),
        product_url:       $(ep).find(".product-title .baobei-name").attr('href'),
        product_pic_url:   $(ep).find(".product-left img").attr('src'),
        product_snapshot:  $(ep).find(".product-snapshot .baobei-name").attr('href'),
        product_count:     $(ep).find(".product-amount span:nth-child(2)").text().trim().slice(1), // remove parcer for different currency
        product_price:     $(ep).find(".product-amount span:first()").text().trim(),
        product_skuid:     $(ep).find(".product-property span:first() span:first()").attr('id'),
        product_property:  $(ep).find(".product-property span:first() span:first()").text().trim(),
        //product_action:    $(ep).find(".product-action span:first()").text().trim(),
        order:             order,
      };
//      console.log($(ep).find(".product-action span:first()").text().trim());
      products.push(product); // local all products
      items.push(product); // global all products
     //   console.log(item);
    });
 //  console.log(products);
  });
/*
  let order = {
    id: $(el).find(".order-info .first-row .info-body ").text().trim(),
    status: $(el).find(".order-status .f-left").text().trim(),
        orderPrice: $(el).find(".amount-num").text().trim(),
        productPriceAndAmount: $(el).find(".product-right .product-amount").text().trim().replace(/(?:\s\s)/g, ""),
        productsNames: products.map((it)=> it.title).join(", "),
	    orderDate: $(el).find(".order-info .second-row .info-body").text().trim(),
	    sellerName: $(el).find(".store-info .first-row .info-body").text().trim(),
        hasTracking: hasTracking,
        products: products,
    };
*/
/*
  if (hasTracking){
    var req = new Promise((resolve, reject) => {
      GM_xmlhttpRequest({
        method: "GET",
        url: "https://ilogisticsaddress.aliexpress.com/ajax_logistics_track.htm?orderId=" + order.id + "&callback=test",
        onload:(data)=>{
          order.tracking = eval(data.responseText).tracking;
          order.trackingNumber = order.tracking.map(it=>it.mailNo).join(", ");
          resolve(order);
          orders.push(order);
        },
        onerror: () => reject(400)
      });
    });
    reqs.push(req);
  } else{
    orders.push(order);
  }
*/
});
//console.log(JSON.stringify(orders));

$.when.apply(null, reqs).done(function(){
  //   console.log(orders);
  // console.log(orders.length);
});
//<button id="search-btn" class="ui-button ui-button-primary search-btn" type="button">Search</button>

$('#mybutton').one('click', function(){
  var r=$('<input/>').attr({
    type:  "button",
    id:    "field",
    value: 'LOAD CSV'
  });
  $("body").append(r);
});

$('<button/>', {
  text: "Copy Orders CSV",
  id: 'csvBtn',
  click: function () {
    $("#csvBtn").text("Loading...");
    Promise.all(reqs).then(o =>{
      var s = "";
      items.forEach(e=> {
        s += e.order.order_id + "\t";
        s += e.order.order_time + "\t";
        s += ((e.order_product_num==1) ? e.order.order_amount : "") + "\t";
        s += e.order.order_status + "\t";
        s += e.order.hasTracking + "\t";
        s += e.order.order_tr_num + "\t";
        s += e.order.order_tr_stat + "\t";
        s += e.order_product_num + "\t";
        s += "\"" + e.product_title + "\"\t";
        s += "\"" + e.product_property + "\"\t";
        s += e.product_count + "\t";
        s += e.product_price + "\t";
        s += e.order.product_action + "\t";
        s += e.product_id + "\t";
        s += ((typeof(e.product_skuid)=='undefined') ? "" : "\"" + e.product_skuid + "\"") + "\t";
        s += e.order.store_name + "\t";
        s += "https:" + e.order.store_url + "\t";
        s += "https:" + e.product_url + "\t";
        s += "\"" + e.product_pic_url + "\"\t";
        s += "https:" + e.product_snapshot + "\t";
        s += "https://trade.aliexpress.com/order_detail.htm?orderId=" + e.order.order_id + "\t";
        s += "\n";

      });
      //console.log(s);
      GM_setClipboard (s);
      $("#csvBtn").text("Orders on clipboard");
    });
  }
}).appendTo("#appeal-alert");

$('<button/>', {
  text: "Copy HEADER",
  id: 'headerBtn',
  click: function () {
    $("#headerBtn").text("Copied!");
    Promise.all(reqs).then(o =>{
      var h = "";
        {
        h += "Order Number" + "\t";
        h += "Order Date" + "\t";
        h += "Total Order Amount" + "\t";
        h += "Order Status" + "\t";
        h += "Tracking Available" + "\t";
        h += "Tracking Number" + "\t";
        h += "Tracking Status" + "\t";
        h += "Item Number of Order" + "\t";
        h += "Item Title" + "\t";
        h += "Item Selections" + "\t";
        h += "Item QTY" + "\t";
        h += "Item Price" + "\t";
        h += "Item Actions" + "\t";
        h += "Item Number" + "\t";
        h += "SKU" + "\t";
        h += "Store Name" + "\t";
        h += "Store URL" + "\t";
        h += "Item URL" + "\t";
        h += "Item Picture URL" + "\t";
        h += "Item Snapshot URL" + "\t";
        h += "Order Detail URL" + "\t";
        };
      GM_setClipboard (h);
      $("#headerBtn").text("Header copied");
    });
  }
}).appendTo("#appeal-alert");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment