-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsyncAmazonToLightspeed.js
77 lines (67 loc) · 2.8 KB
/
syncAmazonToLightspeed.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const refreshToken = require('./lib/functions/lightspeed/refreshToken.js');
const getAccountID = require('./lib/functions/lightspeed/getAccountID.js');
const getOrderIDs = require('./lib/functions/amazon/getOrderIDs.js');
const getOrderItems = require('./lib/functions/amazon/getOrderItems.js');
const getItemIDs = require('./lib/functions/lightspeed/getItemIDs.js');
const createInventoryCount = require('./lib/functions/lightspeed/createInventoryCount.js');
const reconcileInventoryCount = require('./lib/functions/lightspeed/reconcileInventoryCount.js');
const reconcile = require('./lib/functions/database/reconcile.js');
const logger = require('./lib/logger.js');
const syncAmazonToLightspeed = async () => {
return new Promise(async (resolve, reject) => {
// refresh the token
const accessToken = await refreshToken().catch(err => console.error(err));
if (typeof accessToken == 'string') {
// creating the authentication header for all future API calls
const authHeader = {
Authorization: `Bearer ${accessToken}`
};
// getting the account ID
const accountID = await getAccountID(authHeader).catch(err =>
console.error(err)
);
// get a list of order IDs - the time range is measured in minutes: getOrderIDs(minutes)
// the end of the time range is not now but 5 minutes in the past, due to an issue with the MWS API
let orders = await getOrderIDs(authHeader, accountID, 30).catch(err =>
console.error(err)
);
if (orders === undefined || orders.length === 0) {
resolve(false);
return;
}
// get a list of SKUs and their quantities ordered using the order IDs
orders = await getOrderItems(orders).catch(err => console.error(err));
let { orderIDs } = orders;
// get Lightspeed item IDs and current sellable quantities of the order items
orderItems = await getItemIDs(authHeader, accountID).catch(err =>
console.error(err)
);
await reconcile(orderIDs);
if (orderItems[0]) {
// creates an inventory count and fills it with the order items
const inventoryCountID = await createInventoryCount(
authHeader,
accountID,
orderItems
).catch(err => console.error(err));
// reconciles the inventory count, finalizing the sync
// on a 2-second timeout for rate limiting
await reconcileInventoryCount(
authHeader,
accountID,
inventoryCountID
).catch(err => console.error(err));
resolve(true);
} else {
logger.log({
level: 'warn',
message: 'There were no matches, so no inventory count was created'
});
resolve(false);
}
} else {
reject();
}
});
};
module.exports = syncAmazonToLightspeed;