This repository has been archived by the owner on Nov 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
200 lines (158 loc) · 5.16 KB
/
main.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#!/usr/bin/env python3
"""
Amazon Order Alert
"""
__author__ = "Chris Loidolt"
__version__ = "0.1.0"
__license__ = "GNU 3.0"
import requests
import json
import re
import argparse
import uuid
import base64
from datetime import datetime, timedelta
####
## Config
####
shipstation = dict(
API_Key="",
API_Secret="",
orders_endpoint="https://ssapi.shipstation.com/orders?orderStatus=awaiting_shipment",
tag_endpoint="https://ssapi.shipstation.com/orders/addtag",
# Safe shipping timeframe in hours
ship_timeframe=48,
# Tag ID for the urgent tag
tag_id="103434",
)
todoist = dict(
token="",
tasks_endpoint="https://api.todoist.com/rest/v1/tasks",
project_id="",
)
####
## Shipstation
####
def createAuth():
# Create base 64 header auth
userpass = shipstation["API_Key"] + ":" + shipstation["API_Secret"]
encoded_u = base64.b64encode(userpass.encode()).decode()
return encoded_u
def getOrders():
headers = {"Authorization": "Basic %s" % createAuth()}
payload = {}
# Get unshipped orders from shipstation
response = requests.request(
"GET", shipstation["orders_endpoint"], headers=headers, data=payload
)
if response.status_code == 200:
res_dict = response.json()
filterOrders(res_dict)
else:
print("Error code: ")
print(response.status_code)
print(response.raise_for_status())
def filterOrders(orders):
# Iterate through orders
if orders != []:
for index in range(len(orders["orders"])):
# Check if order notes contain an amazon order ID
notes = str(orders["orders"][index]["customerNotes"])
if "Amazon Order ID:" in notes:
print(orders["orders"][index]["orderNumber"])
# Get order date and current timestamp
orderDate = datetime.strptime(
str(orders["orders"][index]["orderDate"]), "%Y-%m-%dT%H:%M:%S.%f0"
)
currentDate = datetime.now()
# Check if order creation date is outside shipping timeframe
difference = currentDate - orderDate
timeframe = timedelta(hours=shipstation["ship_timeframe"])
if difference > timeframe:
# Add urgent tag in shipstation
tagUrgent(orders["orders"][index]["orderId"])
# Create task in todoist
checkExisting(orders["orders"][index]["orderNumber"])
else:
print("Inside shipping window")
else:
print("No Orders")
def tagUrgent(orderId):
headers = {"Authorization": "Basic %s" % createAuth()}
payload = {"orderId": orderId, "tagId": shipstation["tag_id"]}
# Get unshipped orders from shipstation
response = requests.request(
"POST", shipstation["tag_endpoint"], headers=headers, data=payload
)
if response.status_code == 200:
print("Order " + str(orderId) + " tagged as urgent")
else:
print("Error code: ")
print(response.status_code)
print(response.raise_for_status())
####
## Todoist
####
def checkExisting(orderNumber):
headers = {
"Authorization": "Bearer %s" % todoist["token"],
"Content-Type": "application/json",
}
payload = {}
# Get current tasks for project
response = requests.request(
"GET",
todoist["tasks_endpoint"] + "?project_id=" + todoist["project_id"],
headers=headers,
data=payload,
)
# Check if task exists
if response.status_code == 200:
tasks_string = response.text
if tasks_string:
# Build task name string
taskName = "Ship Amazon Order " + str(orderNumber) + " within 24 hours"
# Check if task name exists in dictonary
exists = taskName in tasks_string
if exists:
print("Task for " + str(orderNumber) + " exists, skipping")
else:
# If no matching task exists, create new task
addTask(orderNumber)
else:
print("No Tasks")
else:
print("Error code: ")
print(response.status_code)
print(response.raise_for_status())
def addTask(orderNumber):
headers = {
"Authorization": "Bearer %s" % todoist["token"],
"Content-Type": "application/json",
}
payload = (
'{\r\n "content": "Ship Amazon Order '
+ str(orderNumber)
+ ' within 24 hours",\r\n "project_id":'
+ todoist["project_id"]
+ ',\r\n "due_string": "now",\r\n "due_lang": "en",\r\n "priority": 4\r\n}'
)
# Create task in todoist
response = requests.request(
"POST", todoist["tasks_endpoint"], headers=headers, data=payload,
)
if response.status_code == 200:
print("Todoist task added for order " + str(orderNumber))
else:
print("Error code: ")
print(response.status_code)
print(response.raise_for_status())
####
## Main
####
def main():
""" Main entry point of the app """
getOrders()
if __name__ == "__main__":
""" This is executed when run from the command line """
main()