This repository has been archived by the owner on Oct 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerate.py
130 lines (91 loc) · 4.39 KB
/
generate.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import base64
import datetime
import requests
import os
API_KEY = os.environ["SS_API_KEY"]
API_SECRET = os.environ["SS_API_SECRET"]
STORE_IDS = os.environ.get("SS_STORE_ID", None)
if STORE_IDS:
STORE_IDS = STORE_IDS.split(" ")
def make_authorization_header(key, secret):
encoded = base64.urlsafe_b64encode(f"{key}:{secret}".encode("utf-8"))
return f"Basic {encoded.decode('ascii')}"
class Shipstation:
BASE_URL = "https://ssapi.shipstation.com"
def __init__(self, api_key, api_secret):
self.http = requests.Session()
self.http.headers["Authorization"] = make_authorization_header(api_key, api_secret)
def list_orders(self, store_id=None, order_status=None, page_size=None, page=None):
response = self.http.get(f"{self.BASE_URL}/orders", params={
"storeId": store_id,
"orderStatus": order_status,
"pageSize": page_size,
"page": page,
})
response.raise_for_status()
return response.json()
def list_shipments(self, store_id=None, ship_date_start=None, page_size=None, page=None):
response = self.http.get(f"{self.BASE_URL}/shipments", params={
"storeId": store_id,
"pageSize": page_size,
"page": page,
"shipDateStart": ship_date_start
})
response.raise_for_status()
return response.json()
def list_stores(self):
response = self.http.get(f"{self.BASE_URL}/stores")
response.raise_for_status()
return response.json()
def list_stores(ss):
print("No store specified, please set SS_STORE_ID to one or more of the following:")
stores = ss.list_stores()
for store in stores:
print(f"* {store['storeName']}: {store['storeId']}")
def count_shipped_orders_over_last_month(ss):
start_date = (datetime.date.today() - datetime.timedelta(days=31)).strftime("%Y-%m-%d")
shipments = []
for store_id in STORE_IDS:
results = ss.list_shipments(store_id=store_id, page_size=500, ship_date_start=start_date)
shipments.extend(results["shipments"])
shipments.sort(key=lambda x: x["shipDate"])
last_ship_date = shipments[-1]["shipDate"]
last_ship_date = datetime.datetime.strptime(last_ship_date, "%Y-%m-%d")
last_ship_date = f"{last_ship_date:%B} {last_ship_date.day}"
return len(shipments), last_ship_date
def generate_order_list(ss):
shipped_in_last_month, last_shipped = count_shipped_orders_over_last_month(ss)
orders = []
for store_id in STORE_IDS:
results = ss.list_orders(order_status="awaiting_shipment", store_id=store_id, page_size=500)
orders.extend(results["orders"])
with open("docs/queue.md", "w") as fh:
print(f"We have shipped **{shipped_in_last_month}** orders over the last month, and the last order we shipped went out on {last_shipped}.\n\n", file=fh)
print("| position in queue | order number | order date |", file=fh)
print("| - | - | - |", file=fh)
for n, order in enumerate(orders, 1):
order_date = datetime.datetime.fromisoformat(order["orderDate"].rsplit(".", 1)[0]).date()
combined = "<sup title='This order was combined with another'>*</sup>" if order["advancedOptions"]["mergedOrSplit"] else ""
print(f"| {n} | #{order['orderNumber']} {combined} | {order_date} |", file=fh)
def generate_preorder_list(ss):
orders = []
for store_id in STORE_IDS:
results = ss.list_orders(order_status="on_hold", store_id=store_id, page_size=500)
orders.extend(results["orders"])
with open("docs/preorder-queue.md", "w") as fh:
print("| position in queue | order number | order date |", file=fh)
print("| - | - | - |", file=fh)
for n, order in enumerate(orders, 1):
order_date = datetime.datetime.fromisoformat(order["orderDate"].rsplit(".", 1)[0]).date()
hold_date = datetime.datetime.fromisoformat(order["holdUntilDate"].rsplit(".", 1)[0]).date()
combined = "<sup title='This order was combined with another'>*</sup>" if order["advancedOptions"]["mergedOrSplit"] else ""
print(f"| {n} | #{order['orderNumber']} {combined} | {order_date} |", file=fh)
def main():
ss = Shipstation(API_KEY, API_SECRET)
if STORE_IDS is None:
list_stores(ss)
else:
generate_order_list(ss)
generate_preorder_list(ss)
if __name__ == "__main__":
main()