-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync_inventory.py
80 lines (66 loc) · 2.53 KB
/
sync_inventory.py
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
78
79
80
import os
from collections import OrderedDict
import shopify
from fulfil_client import Client
import sys
# Setup shopify to access the supplier's inventory.
# The shop name can be found from the admin url used for logging in
# This assumes the use of a private app
# See: https://help.shopify.com/manual/apps/private-apps#generate-credentials-from-the-shopify-admin
shop_url = "https://%s:%s@%s.myshopify.com/admin" % (
sys.argv[1], # SHOPIFY_API_KEY
sys.argv[2], # SHOPIFY_PASSWORD
sys.argv[3], # SHOP_NAME
)
shopify.ShopifyResource.set_site(shop_url)
# Setup a connection to Fulfil
fulfil = Client(
sys.argv[4], # FULFIL_SUBDOMAIN
sys.argv[5] # FULFIL_API_KEY
)
ProductSupplier = fulfil.model('purchase.product_supplier')
supplier_code = sys.argv[6] # SUPPLIER_CODE
def fetch_inventory_and_update():
all_supplied_items = ProductSupplier.search_read_all(
# The search filter
[
('party.code', '=', supplier_code)
],
None, # Sort Order
['id', 'code', 'quantity_available']
)
# Make a lookup dictionary for easy access
supplier_items = {}
for item in all_supplied_items:
if not item['code']:
# Skip if there is no supplier sku
continue
supplier_items[item['code'].upper()] = item
print("Found %d items in fulfil by supplier" % len(supplier_items))
# A dictionary to store changes for a bulk update later.
supplier_items_to_update = OrderedDict()
# Get all products from the shopify store
for product in shopify.Product.find():
# browse through each variant
for variant in product.variants:
sku = variant.sku.upper()
if sku not in supplier_items:
continue
item = supplier_items[sku]
if item['quantity_available'] != variant.inventory_quantity:
supplier_items_to_update[item['id']] = variant.inventory_quantity
# Now check if any inventory changes are there to update
if not supplier_items_to_update:
print("No inventory changes to update fulfil with")
return
print("Updating %d supplier items" % len(supplier_items_to_update))
# Call fulfil's bulk update api
bulk_update_args = []
for supplier_item_id, available_qty in supplier_items_to_update.items():
bulk_update_args.append([supplier_item_id])
bulk_update_args.append({
'quantity_available': available_qty,
})
ProductSupplier.write(*bulk_update_args)
if __name__ == '__main__':
fetch_inventory_and_update()