import axios from ‘axios’
export default {
name: “Get Tracking from PN”,
description: “Get Tracking from PN”,
key: “getTrackingFromPN”,
version: “0.0.14”,
type: “action”,
props: {
orders: {
type: “object”,
label: “Orders”
},
location_id: {
type: “string”,
label: “Location Id”
},
store: {
type: “string”,
label: “Shopify Store URL”
},
store_key: {
type: “string”,
label: “Shopify Auth Key”
},
pn_key: {
type: “string”,
label: “Picanova Auth Key”
},
},
async run({$}) {
await synrchoniseOrders(this.orders, this.location_id, this.store, this.store_key, [this.pn](http://this.pn)_key);
async function synrchoniseOrders(orders, location_id, store, store_key, pn_key) {
for(var i in orders) {
var shOrder = orders[i];
var ids = getPicaIds(shOrder.tags);
console.log(ids);
for(var j in ids) {
await getPicaOrder(ids[j].trim(), pn_key)
.then(async (picaOrder) => {
await fulfillOrder(picaOrder, location_id, store);
})
.catch((err) => {
console.log("uncaught error whilst getting pn order: "+ids[j]);
console.log(typeof err.response !== "undefined" ? err.response.data : err);
});
}
}
}
function getPicaIds(tags) {
var tagsArr = tags.split(',');
var ids = [];
for(var i in tagsArr)
if(tagsArr[i].indexOf('PPO') !== -1)
ids.push(tagsArr[i]);
return ids;
}
async function getPicaOrder(id, pn_key) {
var result;
const endpoint = "https://api.picanova.com/api/beta/orders/"+id;
await axios.get(endpoint, { headers: { 'Authorization': 'Basic ' + pn_key }} )
.then((res) => {
console.log("Order with id "+id+" fetched from Picanova");
result = res.data.data;
})
.catch((err) => {
console.log("Error whilst getting order with id " +id+ " from PN");
console.log(typeof err.response !== "undefined" ? err.response.data : err);
});
return result;
}
async function fulfillOrder(picaOrder, id, location_id, store) {
const endpoint = "https://"+store+".[myshopify.com/admin/api/2022-04/orders/](http://myshopify.com/admin/api/2022-04/orders/)" + id + "/fulfillments.json";
const fulfillment = getFulfillment(picaOrder, location_id);
console.log(JSON.stringify(fulfillment));
}
function getFulfillment(picaOrder, location_id) {
return {
"fulfillment": {
"location_id": location_id,
"tracking_company": "",
"tracking_number": "",
"tracking_urls": getTrackingUrls(picaOrder),
"line_items": getItemIds(picaOrder),
"notify_customer": false
}
}
}
function getTrackingUrls(picaOrder) {
var shipments = picaOrder.shipments;
var urls = [];
for(var i in shipments)
urls.push(shipments[i].tracking_url);
return urls;
}
function getItemIds(picaOrder) {
var items = picaOrder.items;
var ids = [];
for(var i in items) {
if(items[i].external_id) {
ids.push({ "id": items[i].external_id });
} else {
console.log("Manual Order deteced");
}
}
return ids;
}
}
}