| 13774 |
amit.gupta |
1 |
# coding=utf-8
|
| 13569 |
amit.gupta |
2 |
'''
|
|
|
3 |
Created on Jan 15, 2015
|
|
|
4 |
|
|
|
5 |
@author: amit
|
|
|
6 |
'''
|
| 13774 |
amit.gupta |
7 |
from base64 import encode
|
|
|
8 |
from bs4 import BeautifulSoup
|
| 17231 |
amit.gupta |
9 |
from datetime import datetime, timedelta, date
|
| 16874 |
amit.gupta |
10 |
from dtr.api.Order import process_rejects
|
| 18028 |
amit.gupta |
11 |
from dtr.dao import Order, SubOrder, AmazonAffiliateInfo, obj
|
| 14464 |
amit.gupta |
12 |
from dtr.main import getStore, Store as MStore, ParseException, getBrowserObject, \
|
| 14624 |
amit.gupta |
13 |
ungzipResponse, tprint
|
| 17307 |
amit.gupta |
14 |
from dtr.storage.DataService import OrdersRaw, Orders, Order_Parse_Info, \
|
| 16986 |
amit.gupta |
15 |
All_user_addresses
|
| 16874 |
amit.gupta |
16 |
from dtr.storage.Mongo import getDealRank
|
| 17307 |
amit.gupta |
17 |
from dtr.utils import utils
|
| 18440 |
amit.gupta |
18 |
from dtr.utils.utils import fetchResponseUsingProxy, readSSh, todict
|
| 16874 |
amit.gupta |
19 |
from elixir import *
|
| 14650 |
amit.gupta |
20 |
import base64
|
| 16874 |
amit.gupta |
21 |
import dtr
|
| 14650 |
amit.gupta |
22 |
import gzip
|
| 14624 |
amit.gupta |
23 |
import mechanize
|
| 14285 |
amit.gupta |
24 |
import os.path
|
| 18376 |
amit.gupta |
25 |
from pyquery import PyQuery as pq
|
| 13774 |
amit.gupta |
26 |
import re
|
| 14033 |
amit.gupta |
27 |
import time
|
| 13809 |
amit.gupta |
28 |
import traceback
|
| 14650 |
amit.gupta |
29 |
import urllib2
|
| 13774 |
amit.gupta |
30 |
|
|
|
31 |
ORDER_REDIRECT_URL = 'https://www.amazon.in/gp/css/summary/edit.html?orderID=%s'
|
| 13810 |
amit.gupta |
32 |
ORDER_SUCCESS_URL = 'https://www.amazon.in/gp/buy/spc/handlers/static-submit-decoupled.html'
|
| 13823 |
amit.gupta |
33 |
THANKYOU_URL = 'https://www.amazon.in/gp/buy/thankyou/handlers/display.html'
|
| 14624 |
amit.gupta |
34 |
AMAZON_AFF_URL = 'https://assoc-datafeeds-eu.amazon.com/datafeed/listReports'
|
| 14650 |
amit.gupta |
35 |
AMAZON_AFF_FILE_URL = 'https://assoc-datafeeds-eu.amazon.com/datafeed/getReport?filename=saholic-21-orders-report-%s.tsv.gz'
|
| 13774 |
amit.gupta |
36 |
class Store(MStore):
|
| 13821 |
amit.gupta |
37 |
|
| 17348 |
amit.gupta |
38 |
orderStatusRegexMap = { MStore.ORDER_PLACED : ['ordered from', 'not yet dispatched','dispatching now', 'preparing for dispatch', 'order received'],
|
| 14064 |
amit.gupta |
39 |
MStore.ORDER_SHIPPED : ['dispatched on','dispatched', 'on the way', 'out for delivery', 'Out for delivery'],
|
| 17324 |
amit.gupta |
40 |
MStore.ORDER_CANCELLED : ['return complete', 'refunded', 'cancelled', 'replacement complete', 'return received'],
|
| 17258 |
amit.gupta |
41 |
MStore.ORDER_DELIVERED : ['delivered', 'your package was delivered', 'package was handed directly to customer']
|
| 13821 |
amit.gupta |
42 |
}
|
| 13774 |
amit.gupta |
43 |
|
|
|
44 |
def __init__(self,store_id):
|
|
|
45 |
super(Store, self).__init__(store_id)
|
|
|
46 |
|
|
|
47 |
def getName(self):
|
| 14749 |
amit.gupta |
48 |
return "amazon"
|
| 13774 |
amit.gupta |
49 |
|
| 14945 |
amit.gupta |
50 |
def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl, track=False):
|
| 17718 |
amit.gupta |
51 |
rawHtml = re.sub(r'[^\x00-\x7F]+',' ', rawHtml)
|
| 14958 |
amit.gupta |
52 |
parseString = "Tracking" if track else "Transacted"
|
|
|
53 |
print parseString, "Order Id to be parsed is :", orderId
|
| 13796 |
amit.gupta |
54 |
resp = {}
|
| 14813 |
amit.gupta |
55 |
resp['result'] = 'ORDER_NOT_CREATED'
|
| 13821 |
amit.gupta |
56 |
if ORDER_SUCCESS_URL in orderSuccessUrl or THANKYOU_URL in orderSuccessUrl:
|
| 13774 |
amit.gupta |
57 |
try:
|
| 17600 |
amit.gupta |
58 |
doc = pq(rawHtml)
|
| 14608 |
amit.gupta |
59 |
try:
|
| 17600 |
amit.gupta |
60 |
orderUrl = doc('a.a-touch-link').attr.href
|
| 14608 |
amit.gupta |
61 |
merchantOrderId = re.findall(r'.*&oid=(.*)&?.*?', orderUrl)[0]
|
|
|
62 |
except:
|
| 17600 |
amit.gupta |
63 |
merchantOrderId = doc("#orders-list>div>span>b").html()
|
| 14699 |
amit.gupta |
64 |
order = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl, True)
|
| 14972 |
amit.gupta |
65 |
order.orderTrackingUrl = ORDER_REDIRECT_URL % (merchantOrderId)
|
|
|
66 |
order.orderSuccessUrl = orderSuccessUrl
|
| 14211 |
amit.gupta |
67 |
order.merchantOrderId = merchantOrderId
|
| 14291 |
amit.gupta |
68 |
order.requireDetail = True
|
| 14698 |
amit.gupta |
69 |
order.status = 'html_required'
|
| 14297 |
amit.gupta |
70 |
order.closed = None
|
| 14312 |
amit.gupta |
71 |
if self._saveToOrder(todict(order)):
|
|
|
72 |
resp['result'] = 'ORDER_CREATED'
|
|
|
73 |
resp["url"] = ORDER_REDIRECT_URL % (merchantOrderId)
|
|
|
74 |
resp["htmlRequired"] = True
|
|
|
75 |
resp['orderId'] = orderId
|
|
|
76 |
else:
|
|
|
77 |
resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
|
|
|
78 |
|
| 13774 |
amit.gupta |
79 |
except:
|
| 14813 |
amit.gupta |
80 |
#Write all cases here for Order Not created Known
|
| 18158 |
amit.gupta |
81 |
soup = BeautifulSoup(rawHtml, "html5lib")
|
| 14809 |
amit.gupta |
82 |
try:
|
| 16874 |
amit.gupta |
83 |
if not soup.body:
|
|
|
84 |
resp['result'] = 'ORDER_NOT_CREATED_KNOWN'
|
| 17359 |
amit.gupta |
85 |
elif 'Securely redirecting you' in soup.find("h3").text.strip() or soup.find("h3").text.strip()=="Orders":
|
| 14813 |
amit.gupta |
86 |
resp['result'] = 'ORDER_NOT_CREATED_KNOWN'
|
| 14809 |
amit.gupta |
87 |
else:
|
| 14813 |
amit.gupta |
88 |
raise
|
| 14809 |
amit.gupta |
89 |
except:
|
| 14814 |
amit.gupta |
90 |
try:
|
| 17356 |
amit.gupta |
91 |
if soup.find("h1").text.strip() in ['This is a duplicate order', 'There was a problem with your payment.', 'Your Orders', 'Your Shopping Cart is empty.', 'Select a payment method', 'Edit quantities'] or "Saved for later" in soup.find("h1").text.strip():
|
| 14814 |
amit.gupta |
92 |
resp['result'] = 'ORDER_NOT_CREATED_KNOWN'
|
|
|
93 |
else:
|
|
|
94 |
raise
|
|
|
95 |
except:
|
| 15046 |
amit.gupta |
96 |
try:
|
| 17356 |
amit.gupta |
97 |
if soup.find("h2").text.strip() in ['Web page not available','Webpage not available', 'Do you have an Amazon password?']:
|
| 15046 |
amit.gupta |
98 |
resp['result'] = 'ORDER_NOT_CREATED_KNOWN'
|
|
|
99 |
else:
|
|
|
100 |
raise
|
|
|
101 |
except:
|
| 15565 |
amit.gupta |
102 |
try:
|
| 16876 |
amit.gupta |
103 |
if soup.find(id="loading-spinner-img") is not None or soup.find(id="anonCarousel1") is not None or soup.find(id="ap_signin_pagelet_title") is not None or soup.find(id="nav-greeting-name") is not None:
|
| 15565 |
amit.gupta |
104 |
resp['result'] = 'ORDER_NOT_CREATED_KNOWN'
|
| 16877 |
amit.gupta |
105 |
elif soup.find("b", {'class':'h1'}).text.strip().find("We're sorry") > -1:
|
|
|
106 |
resp['result'] = 'ORDER_NOT_CREATED_KNOWN'
|
| 15565 |
amit.gupta |
107 |
else:
|
|
|
108 |
raise
|
|
|
109 |
except:
|
|
|
110 |
resp['result'] = 'ORDER_NOT_CREATED_UNKNOWN'
|
|
|
111 |
|
| 13774 |
amit.gupta |
112 |
else:
|
| 13781 |
amit.gupta |
113 |
try:
|
| 14722 |
amit.gupta |
114 |
mo = self.db.merchantOrder.find_one({"orderId":orderId})
|
|
|
115 |
if mo is not None:
|
| 14749 |
amit.gupta |
116 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl, False)
|
| 14722 |
amit.gupta |
117 |
merchantOrder.createdOn = mo.get("createdOn")
|
|
|
118 |
merchantOrder.createdOnInt = mo.get("createdOnInt")
|
|
|
119 |
else:
|
| 14945 |
amit.gupta |
120 |
print "Could not find amazon order with order Id", orderId
|
| 14749 |
amit.gupta |
121 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
|
| 18158 |
amit.gupta |
122 |
soup = BeautifulSoup(rawHtml, "html5lib")
|
| 17331 |
amit.gupta |
123 |
if not soup.body:
|
| 17319 |
amit.gupta |
124 |
resp['result'] = 'DETAIL_NOT_CREATED_KNOWN'
|
|
|
125 |
else:
|
| 14545 |
amit.gupta |
126 |
try:
|
| 17319 |
amit.gupta |
127 |
self.parseNewStlye(merchantOrder, soup)
|
| 15046 |
amit.gupta |
128 |
resp['result'] = 'DETAIL_CREATED'
|
| 14545 |
amit.gupta |
129 |
except:
|
| 15056 |
amit.gupta |
130 |
try:
|
| 17319 |
amit.gupta |
131 |
traceback.print_exc()
|
| 18376 |
amit.gupta |
132 |
self.parseAnotherStlye(merchantOrder, pq(rawHtml))
|
| 17319 |
amit.gupta |
133 |
resp['result'] = 'DETAIL_CREATED'
|
| 15056 |
amit.gupta |
134 |
except:
|
| 15059 |
amit.gupta |
135 |
try:
|
| 18376 |
amit.gupta |
136 |
traceback.print_exc()
|
|
|
137 |
self.parseOldStlye(merchantOrder, soup)
|
|
|
138 |
resp['result'] = 'DETAIL_CREATED'
|
| 15059 |
amit.gupta |
139 |
except:
|
| 18376 |
amit.gupta |
140 |
traceback.print_exc()
|
| 17319 |
amit.gupta |
141 |
try:
|
| 18376 |
amit.gupta |
142 |
self.parseCancelled(merchantOrder, soup)
|
|
|
143 |
resp['result'] = 'ORDER_CANCELLED'
|
| 17319 |
amit.gupta |
144 |
except:
|
| 18376 |
amit.gupta |
145 |
try:
|
|
|
146 |
if soup.find("h1").text.strip() in ["Your Account"] or soup.find("h1").span.text=="Account":
|
|
|
147 |
resp['result'] = 'DETAIL_NOT_CREATED_KNOWN'
|
|
|
148 |
else:
|
|
|
149 |
raise
|
|
|
150 |
except:
|
|
|
151 |
if soup.find(id="ap_signin_pagelet_title").find("h1").text.strip()=="Sign In":
|
|
|
152 |
resp['result'] = 'DETAIL_NOT_CREATED_KNOWN'
|
|
|
153 |
else:
|
|
|
154 |
raise
|
| 17599 |
amit.gupta |
155 |
if resp['result'] == 'DETAIL_NOT_CREATED_KNOWN':
|
| 17357 |
amit.gupta |
156 |
self.db.merchantOrder.update({"orderId":orderId}, {"$set":{"status":"html_required"}})
|
| 13781 |
amit.gupta |
157 |
except:
|
| 17666 |
amit.gupta |
158 |
self.db.merchantOrder.update({"orderId":orderId}, {"$set":{"status":"html_required"}})
|
| 14813 |
amit.gupta |
159 |
print "Error occurred"
|
| 15046 |
amit.gupta |
160 |
resp['result'] = 'DETAIL_NOT_CREATED_UNKNOWN'
|
| 14813 |
amit.gupta |
161 |
traceback.print_exc()
|
| 15046 |
amit.gupta |
162 |
return resp
|
| 13774 |
amit.gupta |
163 |
|
| 13868 |
amit.gupta |
164 |
#This should be exposed from api for specific sources
|
|
|
165 |
def scrapeStoreOrders(self):
|
| 18725 |
amit.gupta |
166 |
orders = self.db.merchantOrder.find({"storeId":1, "closed":False, "subOrders.closed":False, "subOrders.trackingUrl":{"$exists":True}, "subOrders.login":{"$exists":False}})
|
| 14624 |
amit.gupta |
167 |
for merchantOrder in orders:
|
| 14981 |
amit.gupta |
168 |
executeBulk = False
|
| 14624 |
amit.gupta |
169 |
try:
|
|
|
170 |
bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
|
|
171 |
closed = True
|
|
|
172 |
map1 = {}
|
|
|
173 |
for subOrder in merchantOrder.get("subOrders"):
|
|
|
174 |
if subOrder.get("closed"):
|
|
|
175 |
continue
|
|
|
176 |
elif subOrder.get("trackingUrl") is None:
|
|
|
177 |
closed = False
|
|
|
178 |
continue
|
|
|
179 |
findMap = {"orderId":merchantOrder.get("orderId"), "subOrders.merchantSubOrderId":subOrder.get("merchantSubOrderId")}
|
|
|
180 |
trackingUrl = subOrder.get("trackingUrl")
|
|
|
181 |
if not map1.has_key(trackingUrl):
|
| 16468 |
amit.gupta |
182 |
map1[trackingUrl] = self.parseTrackingUrl(trackingUrl, merchantOrder.get("orderId"))
|
| 14624 |
amit.gupta |
183 |
newOrder = map1.get(trackingUrl)
|
| 16474 |
amit.gupta |
184 |
if newOrder:
|
|
|
185 |
executeBulk = True
|
|
|
186 |
updateMap = self.getUpdateMap(newOrder, subOrder.get('cashBackStatus'))
|
|
|
187 |
print findMap, "\n", updateMap
|
|
|
188 |
bulk.find(findMap).update({'$set' : updateMap})
|
|
|
189 |
closed = closed and newOrder['closed']
|
| 14981 |
amit.gupta |
190 |
if executeBulk:
|
| 14697 |
amit.gupta |
191 |
bulk.find({"orderId":merchantOrder.get("orderId")}).update({"$set":{"closed":closed, "parseError":False}})
|
| 14981 |
amit.gupta |
192 |
bulk.execute()
|
| 14624 |
amit.gupta |
193 |
except:
|
| 14847 |
amit.gupta |
194 |
tprint("Could not update " + str(merchantOrder['orderId']) + " For store " + self.getName())
|
| 14692 |
amit.gupta |
195 |
self.db.merchantOrder.update({"orderId":merchantOrder['orderId']}, {"$set":{"parseError":True}})
|
| 14624 |
amit.gupta |
196 |
traceback.print_exc()
|
|
|
197 |
|
| 14608 |
amit.gupta |
198 |
|
|
|
199 |
|
| 14771 |
amit.gupta |
200 |
def parserest(self, soup):
|
|
|
201 |
print "Hi"
|
|
|
202 |
if soup.find('h1'):
|
|
|
203 |
print "OK"
|
| 14608 |
amit.gupta |
204 |
|
| 14464 |
amit.gupta |
205 |
def parseOldStlye(self, merchantOrder, soup):
|
|
|
206 |
merchantOrder.orderTrackingUrl = merchantOrder.orderSuccessUrl
|
|
|
207 |
table = soup.body.findAll("table", recursive=False)[1]
|
|
|
208 |
#print table
|
|
|
209 |
tables = table.tr.td.findAll("table", recursive=False)
|
|
|
210 |
for tr in tables[2].findAll("tr"):
|
|
|
211 |
boldElement = tr.td.b
|
|
|
212 |
if "Order Placed" in str(boldElement):
|
|
|
213 |
merchantOrder.placedOn = boldElement.next_sibling.strip()
|
|
|
214 |
if "order number" in str(boldElement):
|
|
|
215 |
merchantOrder.merchantOrderId = boldElement.next_sibling.strip()
|
|
|
216 |
if "Order Total" in str(boldElement):
|
|
|
217 |
merchantOrder.paidAmount = int(float(boldElement.find('span').contents[-1].replace(',','')))
|
|
|
218 |
anchors = table.tr.td.findAll("a", recursive=False)
|
|
|
219 |
paymentAnchor = anchors.pop(-1)
|
|
|
220 |
|
|
|
221 |
count = 0
|
|
|
222 |
subOrders = []
|
|
|
223 |
merchantOrder.subOrders = subOrders
|
|
|
224 |
counter = 0
|
|
|
225 |
for anchor in anchors:
|
|
|
226 |
count += 1
|
|
|
227 |
tab = anchor.next_sibling
|
|
|
228 |
status = MStore.ORDER_PLACED
|
|
|
229 |
subStr = "Delivery #" + str(count) + ":"
|
|
|
230 |
if subStr in tab.find("b").text:
|
|
|
231 |
detailedStatus = tab.find("b").text.replace(subStr, '').strip()
|
|
|
232 |
|
|
|
233 |
tab = tab.next_sibling.next_sibling
|
|
|
234 |
trs = tab.find("table").find('tbody').findAll("tr", recursive = False)
|
|
|
235 |
|
|
|
236 |
estimatedDelivery = trs[0].td.find("b").next_sibling.strip()
|
|
|
237 |
|
|
|
238 |
orderItemTrs = trs[1].findAll("td", recursive=False)[1].table.tbody.findAll("tr", recursive = False)
|
|
|
239 |
i = -1
|
|
|
240 |
for orderItemTr in orderItemTrs:
|
|
|
241 |
i += 1
|
|
|
242 |
if i%2 == 0:
|
|
|
243 |
continue
|
|
|
244 |
counter += 1
|
|
|
245 |
quantity = int(re.findall(r'\d+', orderItemTr.td.contents[0])[0])
|
|
|
246 |
|
|
|
247 |
productUrl = orderItemTr.td.contents[1].a["href"]
|
|
|
248 |
productTitle = orderItemTr.td.contents[1].a.text
|
|
|
249 |
|
|
|
250 |
unitPrice = int(float(orderItemTr.findAll('td')[1].span.text.replace('Rs. ','').replace(',','')))
|
|
|
251 |
|
|
|
252 |
|
|
|
253 |
subOrder = SubOrder(productTitle, productUrl, merchantOrder.placedOn, unitPrice*quantity, status, quantity)
|
|
|
254 |
subOrder.merchantSubOrderId = str(counter) + " of " + merchantOrder.merchantOrderId
|
|
|
255 |
subOrder.estimatedDeliveryDate = estimatedDelivery
|
| 14722 |
amit.gupta |
256 |
estDlvyTime = datetime.strptime(estimatedDelivery.split('-')[0].strip(), "%A %d %B %Y")
|
|
|
257 |
createdOn = datetime.fromtimestamp(merchantOrder.createdOnInt)
|
|
|
258 |
subOrder.trackAfter = int(time.mktime(max(estDlvyTime-timedelta(days=4),createdOn + timedelta(days=3)).timetuple()))
|
| 14464 |
amit.gupta |
259 |
subOrder.productCode = productUrl.split('/')[5]
|
|
|
260 |
subOrder.detailedStatus = detailedStatus
|
| 18028 |
amit.gupta |
261 |
(cashbackAmount, percentage) = self.getCashbackAmount(subOrder.productCode, unitPrice)
|
| 15346 |
amit.gupta |
262 |
dealRank = getDealRank(subOrder.productCode, self.store_id, merchantOrder.userId)
|
|
|
263 |
subOrder.dealRank = dealRank.get('rank')
|
|
|
264 |
subOrder.rankDesc = dealRank.get('description')
|
| 16283 |
amit.gupta |
265 |
subOrder.maxNlc = dealRank.get('maxNlc')
|
|
|
266 |
subOrder.minNlc = dealRank.get('minNlc')
|
|
|
267 |
subOrder.db = dealRank.get('dp')
|
|
|
268 |
subOrder.itemStatus = dealRank.get('status')
|
| 14464 |
amit.gupta |
269 |
cashbackStatus = Store.CB_PENDING
|
|
|
270 |
if cashbackAmount <= 0:
|
|
|
271 |
cashbackStatus = Store.CB_NA
|
|
|
272 |
subOrder.cashBackStatus = cashbackStatus
|
| 18028 |
amit.gupta |
273 |
subOrder.cashBackAmount = cashbackAmount*quantity
|
| 14464 |
amit.gupta |
274 |
if percentage > 0:
|
|
|
275 |
subOrder.cashBackPercentage = percentage
|
|
|
276 |
subOrders.append(subOrder)
|
|
|
277 |
priceList = paymentAnchor.next_sibling.next_sibling.next_sibling.table.table.tbody.tbody.tbody.findAll('tr', recursive=False)
|
|
|
278 |
totalAmount = 0
|
|
|
279 |
grandAmount = 0
|
|
|
280 |
for price in priceList:
|
|
|
281 |
labelTd = price.td
|
|
|
282 |
if 'Subtotal:' in labelTd.text:
|
|
|
283 |
totalAmount += int(float(labelTd.next_sibling.next_sibling.find('span').contents[-1].replace(',','')))
|
|
|
284 |
elif 'Grand Total:' in labelTd.text:
|
|
|
285 |
grandAmount += int(float(labelTd.next_sibling.next_sibling.find('span').contents[-1].replace(',','')))
|
|
|
286 |
if grandAmount < totalAmount:
|
|
|
287 |
diff = totalAmount - grandAmount
|
|
|
288 |
for subOrder in merchantOrder.subOrders:
|
|
|
289 |
subOrder.amountPaid -= int(diff*(1-subOrder.amountPaid/totalAmount))
|
| 14698 |
amit.gupta |
290 |
merchantOrder.status='success'
|
| 14464 |
amit.gupta |
291 |
self._updateToOrder(todict(merchantOrder))
|
| 18376 |
amit.gupta |
292 |
|
|
|
293 |
def parseAnotherStlye(self, merchantOrder, pqobj):
|
|
|
294 |
counter=0
|
|
|
295 |
detailSection = None
|
|
|
296 |
shipmentSection = None
|
|
|
297 |
summarySection = None
|
|
|
298 |
for el in pqobj('.a-section'):
|
|
|
299 |
if "View order details" in pq(el).text():
|
|
|
300 |
detailSection = pq(el)
|
|
|
301 |
counter += 1
|
|
|
302 |
if "Shipment details" in pq(el).text():
|
|
|
303 |
shipmentSection = pq(el)
|
|
|
304 |
counter += 1
|
|
|
305 |
if "Order Summary" in pq(el).text():
|
|
|
306 |
summarySection = pq(el)
|
|
|
307 |
counter += 1
|
|
|
308 |
if counter == 3:
|
|
|
309 |
break
|
|
|
310 |
|
|
|
311 |
print "detail" if detailSection else "", "shipment" if shipmentSection else "", "summary" if summarySection else ""
|
|
|
312 |
|
|
|
313 |
print pq(detailSection('li .a-row .a-span-last')[0]).text(), pq(detailSection('li .a-row .a-span-last')[1]).text(), pq(detailSection('li .a-row .a-span-last')[2]).text()
|
|
|
314 |
|
|
|
315 |
i=-1
|
|
|
316 |
for s in shipmentSection('.a-box-group'):
|
|
|
317 |
shipmentGroup = pq(s)
|
|
|
318 |
for shipment in shipmentGroup('.a-box'):
|
|
|
319 |
i += 1
|
|
|
320 |
if i==0:
|
|
|
321 |
continue
|
|
|
322 |
shipment = pq(shipment)
|
|
|
323 |
shipmentStatusSection = shipment('.a-section:eq(0)')
|
|
|
324 |
productDetails = shipment('.a-section:eq(1)>.a-row')
|
| 18380 |
amit.gupta |
325 |
print shipmentStatusSection('h3').text(), shipmentStatusSection('p').text(), shipmentStatusSection('span').text()
|
| 18376 |
amit.gupta |
326 |
for productDetail in productDetails:
|
|
|
327 |
productDetail = pq(productDetail)
|
|
|
328 |
pImg = productDetail.children('div').eq(0)
|
|
|
329 |
pQty = productDetail.children('div').eq(1)
|
|
|
330 |
#print pImg('a').attr('href'), pImg('a').attr('title'), pImg('img').attr('src'), pQty('.a-row:nth-child(2)')('span').text().split(':')[1].strip(), pQty('span.currencyINR')
|
| 18725 |
amit.gupta |
331 |
productUrl = pImg('a').attr('href'),
|
|
|
332 |
qty = pQty('.a-row:nth-child(2)')('span').text().split(':')[1].strip()
|
|
|
333 |
price = int(float(pQty('nobr').text().replace('Rs.','').replace(',', '')))
|
|
|
334 |
#subOrder = SubOrder(productTitle, productUrl, merchantOrder.placedOn, amountPaid, MStore.ORDER_PLACED, quantity)
|
| 18376 |
amit.gupta |
335 |
|
|
|
336 |
|
|
|
337 |
raise
|
|
|
338 |
|
|
|
339 |
|
|
|
340 |
merchantOrder.orderTrackingUrl = merchantOrder.orderSuccessUrl
|
|
|
341 |
merchantOrder.placedOn
|
|
|
342 |
merchantOrder.merchantOrderId
|
|
|
343 |
merchantOrder.paidAmount
|
| 14464 |
amit.gupta |
344 |
|
|
|
345 |
def parseNewStlye(self, merchantOrder, soup):
|
|
|
346 |
merchantOrder.orderTrackingUrl = merchantOrder.orderSuccessUrl
|
|
|
347 |
orderDetailsContainer = soup.body.find(id="orderDetails")
|
| 14566 |
amit.gupta |
348 |
divAfterH1 = orderDetailsContainer.h1.next_sibling.next_sibling
|
|
|
349 |
orderLeftDiv = divAfterH1.div
|
| 14464 |
amit.gupta |
350 |
placedOnSpan = orderLeftDiv.find("span", {'class':'order-date-invoice-item'})
|
|
|
351 |
merchantOrder.placedOn =placedOnSpan.text.split('Ordered on')[1].strip()
|
|
|
352 |
merchantOrder.merchantOrderId = placedOnSpan.next_sibling.next_sibling.text.split('Order#')[1].strip()
|
| 15555 |
amit.gupta |
353 |
try:
|
|
|
354 |
priceBox = divAfterH1.next_sibling.next_sibling.next_sibling.next_sibling.find("div", {"class":"a-box-inner"}).div.div.findAll('div', recursive=False)[-1]
|
|
|
355 |
except:
|
|
|
356 |
priceBox = divAfterH1.next_sibling.next_sibling.next_sibling.next_sibling.find("div", {"class":"a-box a-last"}).div.div.findAll('div', recursive=False)[-1]
|
| 14464 |
amit.gupta |
357 |
priceRows = priceBox.findAll('div', {'class':'a-row'})
|
|
|
358 |
subTotal = 0
|
| 14566 |
amit.gupta |
359 |
shippingPrice = 0
|
| 14464 |
amit.gupta |
360 |
promoApplied = 0
|
|
|
361 |
for priceRow in priceRows:
|
|
|
362 |
if "Item(s) Subtotal:" in str(priceRow):
|
|
|
363 |
subTotal = int(float(priceRow.div.next_sibling.next_sibling.span.span.text.replace('Rs.','').replace(',', '')))
|
|
|
364 |
elif "Shipping:" in str(priceRow):
|
|
|
365 |
shippingPrice = int(float(priceRow.div.next_sibling.next_sibling.span.span.text.replace('Rs.','').replace(',', '')))
|
|
|
366 |
elif "Grand Total:" in str(priceRow):
|
|
|
367 |
grandPrice = int(float(priceRow.div.next_sibling.next_sibling.span.span.text.replace('Rs.','').replace(',', '')))
|
|
|
368 |
merchantOrder.paidAmount = grandPrice
|
|
|
369 |
elif "Total:" in str(priceRow):
|
|
|
370 |
totalPrice = int(float(priceRow.div.next_sibling.next_sibling.span.span.text.replace('Rs.','').replace(',', '')))
|
|
|
371 |
elif "Promotion Applied:" in str(priceRow):
|
|
|
372 |
promoApplied += int(float(priceRow.div.next_sibling.next_sibling.span.span.text.replace('Rs.','').replace(',', '')))
|
|
|
373 |
totalPaid = subTotal
|
|
|
374 |
if promoApplied > 0:
|
|
|
375 |
totalPaid -= promoApplied
|
|
|
376 |
if shippingPrice <= promoApplied:
|
|
|
377 |
totalPaid += shippingPrice
|
| 15473 |
amit.gupta |
378 |
|
| 17601 |
amit.gupta |
379 |
shipmentDivs = orderDetailsContainer.findAll('div', class_='shipment')
|
| 14464 |
amit.gupta |
380 |
subOrders = []
|
|
|
381 |
merchantOrder.subOrders = subOrders
|
| 15473 |
amit.gupta |
382 |
closedStatus = True
|
| 17601 |
amit.gupta |
383 |
subOrders = []
|
| 18161 |
amit.gupta |
384 |
j=0
|
| 14464 |
amit.gupta |
385 |
for shipmentDiv in shipmentDivs:
|
| 17601 |
amit.gupta |
386 |
shipmentDiv = shipmentDiv.div
|
| 17361 |
amit.gupta |
387 |
try:
|
|
|
388 |
trackingUrl = 'http://www.amazon.in/' + shipmentDiv.find('span', class_='track-package-button').span.a.get('href')
|
|
|
389 |
except:
|
|
|
390 |
trackingUrl= None
|
|
|
391 |
|
| 17347 |
amit.gupta |
392 |
deliverySpanTop = None
|
| 14464 |
amit.gupta |
393 |
innerBoxes = shipmentDiv.findAll('div', recursive = False)
|
|
|
394 |
statusDiv = innerBoxes[0]
|
|
|
395 |
subOrderStatus = statusDiv.div.span.text.strip()
|
| 17347 |
amit.gupta |
396 |
try:
|
|
|
397 |
deliverySpanTop = statusDiv.div.div.find_next_sibling('div').span
|
|
|
398 |
except:
|
| 17617 |
amit.gupta |
399 |
pass
|
| 18030 |
amit.gupta |
400 |
#if not deliverySpanTop:
|
|
|
401 |
productDivs = innerBoxes[-1].div.div.findAll('div', recursive=False)
|
| 14464 |
amit.gupta |
402 |
merchantOrder.subOrders = subOrders
|
|
|
403 |
for i, productDiv in enumerate(productDivs):
|
| 17347 |
amit.gupta |
404 |
deliverySpan = deliverySpanTop
|
|
|
405 |
if not deliverySpanTop:
|
|
|
406 |
if i%2==1:
|
|
|
407 |
continue
|
| 18028 |
amit.gupta |
408 |
deliverySpan = productDiv.div.div.span
|
| 18156 |
amit.gupta |
409 |
try:
|
|
|
410 |
productDiv = productDivs[i+1]
|
|
|
411 |
except:
|
|
|
412 |
pass
|
| 18028 |
amit.gupta |
413 |
for prodRow in productDiv.findAll('div', recursive=False):
|
|
|
414 |
j += 1
|
|
|
415 |
imgDiv = prodRow.div.div
|
|
|
416 |
detailDiv = imgDiv.find_next_sibling('div')
|
|
|
417 |
detailDivs = detailDiv.findAll('div', recursive=False)
|
|
|
418 |
arr = re.split("^(\d+) of", detailDivs[0].a.text.strip())
|
|
|
419 |
(productTitle, quantity) = (arr[-1], (1 if len(arr)<2 else int(arr[1])) )
|
| 14756 |
amit.gupta |
420 |
try:
|
| 18028 |
amit.gupta |
421 |
unitPrice = int(float(detailDivs[2].span.text.replace('Rs. ','').replace(',','')))
|
| 14756 |
amit.gupta |
422 |
except:
|
| 18028 |
amit.gupta |
423 |
unitPrice = int(float(detailDivs[3].span.text.replace('Rs. ','').replace(',','')))
|
|
|
424 |
amountPaid = int((unitPrice*quantity*totalPaid)/subTotal)
|
|
|
425 |
productUrl = "http://www.amazon.in" + detailDivs[0].a.get('href')
|
|
|
426 |
subOrder = SubOrder(productTitle, productUrl, merchantOrder.placedOn, amountPaid, MStore.ORDER_PLACED, quantity)
|
|
|
427 |
subOrder.productCode = productUrl.split('/')[5]
|
|
|
428 |
subOrder.unitPrice = unitPrice
|
|
|
429 |
subOrder.merchantSubOrderId = str(j) + " of " + merchantOrder.merchantOrderId
|
|
|
430 |
estDlvyTime = datetime.now()
|
|
|
431 |
if deliverySpan is not None:
|
|
|
432 |
try:
|
|
|
433 |
subOrder.estimatedDeliveryDate = deliverySpan.span.text.strip()
|
|
|
434 |
estDate = subOrder.estimatedDeliveryDate.split("-")[0].strip()
|
|
|
435 |
subOrder.estimatedDeliveryInt = int(time.mktime((datetime.strptime(estDate, "%A %d %B %Y")).timetuple()))
|
|
|
436 |
estDlvyTime = datetime.strptime(estDate, "%A %d %B %Y")
|
|
|
437 |
except:
|
|
|
438 |
if "Delivered on" in deliverySpan.text:
|
|
|
439 |
subOrder.deliveredOn = deliverySpan.text.split(":")[1].strip()
|
|
|
440 |
subOrder.estimatedDeliveryDate = "Not available"
|
|
|
441 |
|
|
|
442 |
createdOn = datetime.fromtimestamp(merchantOrder.createdOnInt)
|
|
|
443 |
subOrder.trackAfter = int(time.mktime(max(estDlvyTime-timedelta(days=4),createdOn + timedelta(days=3)).timetuple()))
|
|
|
444 |
subOrder.detailedStatus = subOrderStatus
|
|
|
445 |
status=MStore.ORDER_PLACED
|
| 17599 |
amit.gupta |
446 |
try:
|
| 18028 |
amit.gupta |
447 |
status = self._getStatusFromDetailedStatus(subOrderStatus)
|
| 17599 |
amit.gupta |
448 |
except:
|
|
|
449 |
try:
|
| 18028 |
amit.gupta |
450 |
dateString = subOrderStatus.split("Delivered ")[1].strip()
|
|
|
451 |
subOrder.status = MStore.ORDER_DELIVERED
|
|
|
452 |
subOrder.detailedStatus = 'Delivered'
|
|
|
453 |
dateString = getDateStringDelivered(dateString)
|
| 17631 |
amit.gupta |
454 |
if dateString is not None:
|
| 18028 |
amit.gupta |
455 |
subOrder.deliveredOn = datetime.strftime(dateString, '%d-%b-%y')
|
| 17599 |
amit.gupta |
456 |
except:
|
| 18028 |
amit.gupta |
457 |
try:
|
|
|
458 |
dateString = subOrderStatus.split("Arriving ")[1].split("by")[0].strip()
|
|
|
459 |
subOrder.status = MStore.ORDER_SHIPPED
|
|
|
460 |
dateString = getDateStringArriving(dateString)
|
|
|
461 |
if dateString is not None:
|
|
|
462 |
subOrder.deliveryEstimate = datetime.strftime(dateString, '%d-%b-%y')
|
|
|
463 |
else:
|
|
|
464 |
subOrder.deliveryEstimate = subOrderStatus.split("Arriving ")[1].split("by")[0].strip()
|
|
|
465 |
except:
|
|
|
466 |
print "Unknown status Alert -", status
|
|
|
467 |
|
|
|
468 |
subOrder.deliveryCharges = shippingPrice
|
|
|
469 |
if trackingUrl:
|
| 18156 |
amit.gupta |
470 |
subOrder.trackingUrl = trackingUrl
|
| 18028 |
amit.gupta |
471 |
subOrder.imgUrl = imgDiv.img["src"]
|
|
|
472 |
(cashbackAmount, percentage) = self.getCashbackAmount(subOrder.productCode, amountPaid/quantity)
|
|
|
473 |
dealRank = getDealRank(subOrder.productCode, self.store_id, merchantOrder.userId)
|
|
|
474 |
subOrder.dealRank = dealRank.get('rank')
|
|
|
475 |
subOrder.rankDesc = dealRank.get('description')
|
| 18384 |
amit.gupta |
476 |
subOrder.maxNlc = dealRank.get('maxNlc')
|
|
|
477 |
subOrder.minNlc = dealRank.get('minNlc')
|
|
|
478 |
subOrder.db = dealRank.get('dp')
|
|
|
479 |
subOrder.itemStatus = dealRank.get('status')
|
| 18028 |
amit.gupta |
480 |
cashbackStatus = Store.CB_PENDING
|
|
|
481 |
if cashbackAmount <= 0:
|
|
|
482 |
cashbackStatus = Store.CB_NA
|
|
|
483 |
subOrder.cashBackStatus = cashbackStatus
|
|
|
484 |
subOrder.cashBackAmount = cashbackAmount*quantity
|
|
|
485 |
if percentage > 0:
|
|
|
486 |
subOrder.cashBackPercentage = percentage
|
|
|
487 |
if hasattr(subOrder, 'deliveredOn') or subOrder.status==Store.ORDER_DELIVERED:
|
|
|
488 |
subOrder.status = Store.ORDER_DELIVERED
|
|
|
489 |
subOrder.closed = True
|
|
|
490 |
if subOrder.cashBackStatus == Store.CB_PENDING:
|
|
|
491 |
subOrder.cashBackStatus = Store.CB_APPROVED
|
|
|
492 |
elif closedStatus:
|
|
|
493 |
closedStatus= False
|
|
|
494 |
subOrders.append(subOrder)
|
| 14698 |
amit.gupta |
495 |
merchantOrder.status='success'
|
| 15473 |
amit.gupta |
496 |
merchantOrder.closed = closedStatus
|
| 14464 |
amit.gupta |
497 |
self._updateToOrder(todict(merchantOrder))
|
| 14545 |
amit.gupta |
498 |
|
|
|
499 |
def parseCancelled(self, merchantOrder,soup):
|
| 14722 |
amit.gupta |
500 |
try:
|
|
|
501 |
fonts = soup.body.findAll("table", recursive=False)[1].findAll("font")
|
|
|
502 |
if fonts[0].text == "Important Message":
|
|
|
503 |
if fonts[1].text=="This order has been cancelled.":
|
|
|
504 |
merchantOrder.closed = True
|
|
|
505 |
merchantOrder.status = "cancelled"
|
|
|
506 |
merchantOrder.requireDetail = False
|
|
|
507 |
self._updateToOrder(todict(merchantOrder))
|
|
|
508 |
return
|
|
|
509 |
else:
|
|
|
510 |
raise ParseException("parseCancelled", "Found detailed status" + fonts[1].text)
|
| 14545 |
amit.gupta |
511 |
else:
|
|
|
512 |
raise ParseException("parseCancelled", "Found detailed status" + fonts[1].text)
|
| 14722 |
amit.gupta |
513 |
except:
|
| 14549 |
amit.gupta |
514 |
orderDetails = soup.body.find(id="orderDetails")
|
|
|
515 |
if orderDetails is not None and orderDetails.h4.text == "This order has been cancelled.":
|
|
|
516 |
merchantOrder.closed = True
|
| 14698 |
amit.gupta |
517 |
merchantOrder.status = "cancelled"
|
| 14549 |
amit.gupta |
518 |
merchantOrder.requireDetail = False
|
|
|
519 |
self._updateToOrder(todict(merchantOrder))
|
|
|
520 |
else:
|
|
|
521 |
raise ParseException("parseCancelled", "Found detailed status" + fonts[1].text)
|
| 14464 |
amit.gupta |
522 |
|
| 13868 |
amit.gupta |
523 |
def getTrackingUrls(self, userId):
|
| 14074 |
amit.gupta |
524 |
|
|
|
525 |
missingOrderUrls = []
|
|
|
526 |
missingOrders = self._getMissingOrders({'userId':userId})
|
|
|
527 |
for missingOrder in missingOrders:
|
|
|
528 |
missingOrderUrls.append(ORDER_REDIRECT_URL%(missingOrder['merchantOrderId']))
|
| 17453 |
amit.gupta |
529 |
orders = self._getActiveOrders({'userId':userId})
|
| 13882 |
amit.gupta |
530 |
count = len(orders)
|
| 13879 |
amit.gupta |
531 |
print "count", count
|
| 14948 |
amit.gupta |
532 |
print "Missing Urls"
|
|
|
533 |
print "*************"
|
|
|
534 |
print missingOrderUrls
|
| 13868 |
amit.gupta |
535 |
if count > 0:
|
| 14684 |
amit.gupta |
536 |
return missingOrderUrls + ['https://www.amazon.in/gp/css/order-history', 'https://www.amazon.in/gp/css/order-history/?orderFilter=cancelled', 'https://www.amazon.in/gp/css/order-history/?orderFilter=cancelled&startIndex=10']
|
| 13959 |
amit.gupta |
537 |
else:
|
| 14074 |
amit.gupta |
538 |
return missingOrderUrls
|
| 13927 |
amit.gupta |
539 |
|
|
|
540 |
def trackOrdersForUser(self, userId, url, rawHtml):
|
| 17718 |
amit.gupta |
541 |
rawHtml = re.sub(r'[^\x00-\x7F]+',' ', rawHtml)
|
| 14985 |
amit.gupta |
542 |
directory = "/AmazonTrack/User" + str(userId)
|
| 14285 |
amit.gupta |
543 |
if not os.path.exists(directory):
|
|
|
544 |
os.makedirs(directory)
|
| 14173 |
amit.gupta |
545 |
|
| 14945 |
amit.gupta |
546 |
|
| 13995 |
amit.gupta |
547 |
try:
|
|
|
548 |
searchMap = {'userId':userId}
|
|
|
549 |
collectionMap = {'merchantOrderId':1}
|
|
|
550 |
activeOrders = self._getActiveOrders(searchMap, collectionMap)
|
| 14033 |
amit.gupta |
551 |
datetimeNow = datetime.now()
|
|
|
552 |
timestamp = int(time.mktime(datetimeNow.timetuple()))
|
| 14009 |
amit.gupta |
553 |
print "url----------------", url
|
| 17465 |
amit.gupta |
554 |
cancelledSummary = False
|
| 14320 |
amit.gupta |
555 |
if url == 'https://www.amazon.in/gp/css/order-history' or 'https://www.amazon.in/gp/css/order-history/?orderFilter=cancelled' in url:
|
| 14945 |
amit.gupta |
556 |
if url == 'https://www.amazon.in/gp/css/order-history':
|
|
|
557 |
filename = directory + "/orderSummary" + datetime.strftime(datetime.now(), '%d-%m:%H:%M:%S')
|
|
|
558 |
else:
|
| 17465 |
amit.gupta |
559 |
filename = directory + "/cancelledSummary" + datetime.strftime(datetime.now(), '%d-%m:%H:%M:%S')
|
|
|
560 |
cancelledSummary = True
|
| 14945 |
amit.gupta |
561 |
f = open(filename,'w')
|
|
|
562 |
f.write(rawHtml) # python will convert \n to os.linesep
|
|
|
563 |
f.close() # you can omit in most cases as the destructor will call if
|
| 18158 |
amit.gupta |
564 |
soup = BeautifulSoup(rawHtml,'html5lib')
|
| 13995 |
amit.gupta |
565 |
allOrders = soup.find(id="ordersContainer").findAll('div', {'class':'a-box-group a-spacing-base order'})
|
|
|
566 |
bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
|
|
567 |
for activeOrder in activeOrders:
|
| 17307 |
amit.gupta |
568 |
matched=False
|
| 13995 |
amit.gupta |
569 |
for orderEle in allOrders:
|
| 17254 |
amit.gupta |
570 |
deliveredOn = None
|
|
|
571 |
deliveryEstimate = None
|
| 17258 |
amit.gupta |
572 |
shippingEstimate = None
|
| 13995 |
amit.gupta |
573 |
orderdiv = orderEle.find('div', {'class':'a-box a-color-offset-background order-info'}).find('div', {'class':'a-fixed-right-grid-col actions a-col-right'})
|
|
|
574 |
merchantOrderId = orderdiv.find('span', {'class':'a-color-secondary value'}).text.strip()
|
|
|
575 |
if merchantOrderId==activeOrder['merchantOrderId']:
|
| 17307 |
amit.gupta |
576 |
matched=True
|
| 13995 |
amit.gupta |
577 |
closed = True
|
| 17465 |
amit.gupta |
578 |
if not cancelledSummary:
|
|
|
579 |
shipments = orderEle.findAll('div',{'class':re.compile('.*?shipment.*?')}, recursive=False)
|
|
|
580 |
else:
|
|
|
581 |
shipments = orderEle.findAll('div',{'class':re.compile('.*?a-box.*?')}, recursive=False)
|
|
|
582 |
shipments.pop(0)
|
| 13995 |
amit.gupta |
583 |
for shipment in shipments:
|
| 17307 |
amit.gupta |
584 |
orderStatusDesc = None
|
| 13995 |
amit.gupta |
585 |
shipdiv = shipment.find('div', {'class':'a-box-inner'})
|
| 14050 |
amit.gupta |
586 |
sdivs = shipment.div.div.findAll('div', recursive=False)
|
| 17254 |
amit.gupta |
587 |
try:
|
| 17270 |
amit.gupta |
588 |
orderStatus = sdivs[0].span.text.strip()
|
|
|
589 |
status = self._getStatusFromDetailedStatus(orderStatus)
|
| 17254 |
amit.gupta |
590 |
except:
|
| 17270 |
amit.gupta |
591 |
try:
|
|
|
592 |
dateString = orderStatus.split("Delivered ")[1].strip()
|
|
|
593 |
status = MStore.ORDER_DELIVERED
|
|
|
594 |
deliveredOn = datetime.strftime(getDateStringDelivered(dateString), '%d-%b-%y')
|
|
|
595 |
except:
|
|
|
596 |
try:
|
| 17271 |
amit.gupta |
597 |
dateString = sdivs[0].span.text.strip().split("Arriving ")[1].split("by")[0].strip()
|
| 17270 |
amit.gupta |
598 |
status = MStore.ORDER_SHIPPED
|
|
|
599 |
deliveryEstimate = datetime.strftime(getDateStringArriving(dateString), '%d-%b-%y')
|
|
|
600 |
except:
|
|
|
601 |
print "Unknown status Alert -", orderStatus
|
| 17348 |
amit.gupta |
602 |
print merchantOrderId, "Order Status", orderStatus
|
| 17256 |
amit.gupta |
603 |
try:
|
| 17270 |
amit.gupta |
604 |
orderStatusDesc = sdivs[0].findAll('div')[1].div.text.strip()
|
|
|
605 |
except:
|
| 17271 |
amit.gupta |
606 |
try:
|
|
|
607 |
orderStatusDesc = sdivs[0].findAll('div')[1].text.strip()
|
|
|
608 |
except:
|
| 17307 |
amit.gupta |
609 |
print "Order Status Description None or empty for", merchantOrderId, "and User", userId
|
| 17270 |
amit.gupta |
610 |
|
| 17271 |
amit.gupta |
611 |
if orderStatusDesc:
|
| 17348 |
amit.gupta |
612 |
print merchantOrderId, "Order status desc", orderStatusDesc
|
| 17271 |
amit.gupta |
613 |
try:
|
| 17348 |
amit.gupta |
614 |
status = self._getStatusFromDetailedStatus(orderStatus)
|
|
|
615 |
except:
|
|
|
616 |
pass
|
|
|
617 |
try:
|
| 17271 |
amit.gupta |
618 |
if "Dispatch estimate" in orderStatusDesc:
|
|
|
619 |
shippingEstimate = orderStatus.split("Dispatch estimate").split("-")[0].strip()
|
|
|
620 |
elif "Delivery estimate" in orderStatus:
|
|
|
621 |
deliveryEstimate = orderStatus.split("Delivery estimate").split("-")[0].strip()
|
|
|
622 |
elif "Arriving" in orderStatus:
|
|
|
623 |
deliveryEstimate = datetime.strftime(getDateStringArriving(orderStatus.split("Arriving")[1].strip().split("by")[0].strip()), '%d-%b-%y')
|
|
|
624 |
except:
|
|
|
625 |
print "Could not find anything relevent for merchantOrder", merchantOrderId, "and User", userId
|
|
|
626 |
closed=False
|
|
|
627 |
status = None
|
| 17258 |
amit.gupta |
628 |
|
| 14335 |
amit.gupta |
629 |
productDivs = shipdiv.find('div', {'class':re.compile('.*?a-spacing-top-medium.*?')}).find('div', {'class':'a-row'}).findAll('div', recursive=False)
|
| 13995 |
amit.gupta |
630 |
trackingUrl = None
|
|
|
631 |
for buttonDiv in shipdiv.findAll('span', {'class':'a-button-inner'}):
|
|
|
632 |
if buttonDiv.find('a').text.strip()=='Track package':
|
|
|
633 |
trackingUrl = buttonDiv.find('a')['href'].strip()
|
|
|
634 |
if not trackingUrl.startswith("http"):
|
| 14608 |
amit.gupta |
635 |
trackingUrl = "http://www.amazon.in" + trackingUrl
|
| 13995 |
amit.gupta |
636 |
break
|
|
|
637 |
for prodDiv in productDivs:
|
|
|
638 |
prodDiv.find('div', {'class':'a-fixed-left-grid-inner'})
|
|
|
639 |
productTitle = prodDiv.find('div', {'class':'a-fixed-left-grid-inner'}).find("div", {'class':'a-row'}).find('a').text.strip()
|
|
|
640 |
imgUrl = prodDiv.find("img")["src"]
|
|
|
641 |
for subOrder in activeOrder['subOrders']:
|
| 17307 |
amit.gupta |
642 |
if subOrder['closed']==True:
|
|
|
643 |
continue
|
| 17230 |
amit.gupta |
644 |
if subOrder['productTitle'] in productTitle:
|
| 13995 |
amit.gupta |
645 |
findMap = {"orderId": activeOrder['orderId'], "subOrders.merchantSubOrderId": subOrder.get("merchantSubOrderId")}
|
|
|
646 |
updateMap = {}
|
|
|
647 |
closedStatus = False
|
|
|
648 |
updateMap['subOrders.$.imgUrl'] = imgUrl
|
| 14033 |
amit.gupta |
649 |
updateMap['subOrders.$.lastTracked'] = timestamp
|
| 17258 |
amit.gupta |
650 |
if status:
|
| 17348 |
amit.gupta |
651 |
updateMap['subOrders.$.detailedStatus'] = orderStatus
|
| 17258 |
amit.gupta |
652 |
updateMap['subOrders.$.status'] = status
|
|
|
653 |
cashbackStatus = subOrder.get("cashBackStatus")
|
| 13995 |
amit.gupta |
654 |
|
| 17251 |
amit.gupta |
655 |
if status==MStore.ORDER_DELIVERED:
|
| 17271 |
amit.gupta |
656 |
if deliveredOn:
|
| 17254 |
amit.gupta |
657 |
updateMap['subOrders.$.deliveredOn'] = deliveredOn
|
| 13995 |
amit.gupta |
658 |
closedStatus = True
|
|
|
659 |
updateMap['subOrders.$.closed'] = True
|
|
|
660 |
if cashbackStatus == Store.CB_PENDING:
|
| 14607 |
amit.gupta |
661 |
updateMap['subOrders.$.cashBackStatus'] = Store.CB_APPROVED
|
| 13995 |
amit.gupta |
662 |
if status==MStore.ORDER_CANCELLED:
|
|
|
663 |
closedStatus = True
|
|
|
664 |
updateMap['subOrders.$.closed'] = True
|
|
|
665 |
if cashbackStatus == Store.CB_PENDING:
|
|
|
666 |
updateMap['subOrders.$.cashBackStatus'] = Store.CB_CANCELLED
|
| 17254 |
amit.gupta |
667 |
if status==MStore.ORDER_SHIPPED:
|
|
|
668 |
if deliveryEstimate:
|
|
|
669 |
updateMap['subOrders.$.estimatedDeliveryDate'] = deliveryEstimate
|
| 13995 |
amit.gupta |
670 |
if trackingUrl is not None:
|
|
|
671 |
updateMap['subOrders.$.trackingUrl'] = trackingUrl
|
| 17322 |
amit.gupta |
672 |
updateMap['subOrders.$.trackMissing'] = False
|
| 17258 |
amit.gupta |
673 |
if shippingEstimate:
|
|
|
674 |
updateMap['subOrders.$.estimatedShippingDate'] = shippingEstimate
|
| 13995 |
amit.gupta |
675 |
if not closedStatus:
|
|
|
676 |
closed = False
|
| 17307 |
amit.gupta |
677 |
#{"subOrders.closed":False,"subOrders.trackingUrl":{"$exists":False},"subOrders.trackAfter":{"$lt":utils.getCurrTimeStamp()}
|
| 17359 |
amit.gupta |
678 |
updateMap['status']='success'
|
| 13995 |
amit.gupta |
679 |
bulk.find(findMap).update({'$set' : updateMap})
|
|
|
680 |
break
|
| 17321 |
amit.gupta |
681 |
bulk.find({'orderId': activeOrder['orderId']}).update({"$set":{'closed':closed}})
|
| 17307 |
amit.gupta |
682 |
break
|
|
|
683 |
if not matched:
|
| 17319 |
amit.gupta |
684 |
updateMap = {'subOrders.$.trackMissing': True}
|
| 17307 |
amit.gupta |
685 |
for subOrder in activeOrder['subOrders']:
|
|
|
686 |
if subOrder['closed']==True:
|
|
|
687 |
continue
|
|
|
688 |
findMap = {"orderId": activeOrder['orderId'], "subOrders.merchantSubOrderId": subOrder.get("merchantSubOrderId"),
|
|
|
689 |
"subOrders.trackAfter":{"$lt":utils.getCurrTimeStamp()}}
|
|
|
690 |
bulk.find({'orderId': activeOrder['orderId']})
|
|
|
691 |
bulk.find(findMap).update({'$set':updateMap})
|
| 14080 |
amit.gupta |
692 |
bulk.execute()
|
|
|
693 |
return 'PARSED_SUCCESS'
|
|
|
694 |
else:
|
| 15563 |
amit.gupta |
695 |
merchantOrderId = re.findall(r'https://www.amazon.in/gp/css/summary/edit.html\?orderID=(.*)?', url, re.IGNORECASE)[0]
|
|
|
696 |
print "merchantOrderId", merchantOrderId
|
| 14085 |
amit.gupta |
697 |
merchantOrder = self.db.merchantOrder.find_one({"merchantOrderId":merchantOrderId})
|
| 14945 |
amit.gupta |
698 |
|
|
|
699 |
filename = directory + "/" + merchantOrderId
|
|
|
700 |
f = open(filename,'w')
|
|
|
701 |
f.write(rawHtml) # python will convert \n to os.linesep
|
|
|
702 |
f.close() # you can omit in most cases as the destructor will call if
|
| 15555 |
amit.gupta |
703 |
result = self.parseOrderRawHtml(merchantOrder['orderId'], merchantOrder['subTagId'], merchantOrder['userId'], rawHtml, url, True)['result']
|
| 15562 |
amit.gupta |
704 |
print "result", result
|
| 15555 |
amit.gupta |
705 |
try:
|
| 15560 |
amit.gupta |
706 |
order1 = session.query(OrdersRaw).filter_by(id=merchantOrder['orderId']).first()
|
|
|
707 |
order1.status = result
|
|
|
708 |
order1.rawhtml = rawHtml
|
| 17358 |
amit.gupta |
709 |
order1.order_url = url
|
| 15555 |
amit.gupta |
710 |
session.commit()
|
| 15561 |
amit.gupta |
711 |
except:
|
|
|
712 |
traceback.print_exc()
|
| 15555 |
amit.gupta |
713 |
finally:
|
|
|
714 |
session.close()
|
| 14080 |
amit.gupta |
715 |
return 'PARSED_SUCCESS'
|
|
|
716 |
pass
|
| 14008 |
amit.gupta |
717 |
return 'PARSED_SUCCESS_NO_ORDERS'
|
| 13995 |
amit.gupta |
718 |
except:
|
|
|
719 |
traceback.print_exc()
|
|
|
720 |
return 'PARSED_FAILED'
|
|
|
721 |
|
|
|
722 |
def _getStatusFromDetailedStatus(self, detailedStatus):
|
| 14061 |
amit.gupta |
723 |
if "ordered from" in detailedStatus.lower():
|
|
|
724 |
return MStore.ORDER_PLACED
|
|
|
725 |
|
| 13995 |
amit.gupta |
726 |
for key, value in self.orderStatusRegexMap.iteritems():
|
| 14032 |
amit.gupta |
727 |
if detailedStatus.lower() in value:
|
| 13995 |
amit.gupta |
728 |
return key
|
|
|
729 |
|
| 17253 |
amit.gupta |
730 |
print "Detailed Status need to be mapped", "Store:", self.store_id, detailedStatus
|
| 13995 |
amit.gupta |
731 |
raise ParseException("_getStatusFromDetailedStatus", "Found new order status" + detailedStatus)
|
| 14624 |
amit.gupta |
732 |
def scrapeAffiliate(self, startDate=None, endDate=None):
|
| 14650 |
amit.gupta |
733 |
br = getBrowserObject()
|
|
|
734 |
br.add_password('https://assoc-datafeeds-eu.amazon.com', 'Saholic', 'Fnubyvp')
|
|
|
735 |
url = AMAZON_AFF_URL
|
|
|
736 |
response = br.open(url)
|
|
|
737 |
#get data for past 40 days and store it to mongo
|
|
|
738 |
dt = datetime.now()
|
| 14701 |
amit.gupta |
739 |
dat = dt - timedelta(days=2)
|
| 14651 |
amit.gupta |
740 |
url = AMAZON_AFF_FILE_URL%(datetime.strftime(dat, "%Y%m%d"))
|
|
|
741 |
response = br.open(url)
|
|
|
742 |
page = gzip.GzipFile(fileobj=response, mode='rb').read()
|
|
|
743 |
j=-1
|
|
|
744 |
for row in page.split("\n"):
|
|
|
745 |
j += 1
|
|
|
746 |
if j== 0 or j==1:
|
|
|
747 |
continue
|
|
|
748 |
fields = row.split("\t")
|
|
|
749 |
if len(fields)>1:
|
|
|
750 |
print fields
|
|
|
751 |
amazonAffiliate = AmazonAffiliateInfo(fields[0], fields[1], fields[2], fields[3], fields[4], fields[5], fields[6], fields[7], fields[8], fields[9])
|
|
|
752 |
print amazonAffiliate
|
|
|
753 |
self.db.amazonAffiliateInfo.insert(todict(amazonAffiliate))
|
|
|
754 |
else:
|
|
|
755 |
break
|
| 14650 |
amit.gupta |
756 |
|
| 14608 |
amit.gupta |
757 |
|
| 16468 |
amit.gupta |
758 |
def parseTrackingUrl(self, trackingUrl, orderId):
|
| 16474 |
amit.gupta |
759 |
print trackingUrl
|
| 14624 |
amit.gupta |
760 |
subOrder = {}
|
| 14749 |
amit.gupta |
761 |
page = fetchResponseUsingProxy(trackingUrl)
|
| 16468 |
amit.gupta |
762 |
status = MStore.ORDER_SHIPPED
|
|
|
763 |
#print page
|
| 14624 |
amit.gupta |
764 |
soup = BeautifulSoup(page)
|
| 16468 |
amit.gupta |
765 |
header1 = soup.find("h1")
|
|
|
766 |
if header1:
|
| 18727 |
amit.gupta |
767 |
if header1.text=="Sign In" or header1.text.strip()=="Login":
|
| 16468 |
amit.gupta |
768 |
print "Login page is displayed for order id", orderId
|
| 17307 |
amit.gupta |
769 |
self.db.merchantOrder.update({"orderId":orderId}, {"$set":{"trackError":True}})
|
| 18725 |
amit.gupta |
770 |
subOrder['login'] = True
|
| 14624 |
amit.gupta |
771 |
return subOrder
|
| 16468 |
amit.gupta |
772 |
try:
|
| 16474 |
amit.gupta |
773 |
print "Tracking page is displayed for order id", orderId
|
| 16468 |
amit.gupta |
774 |
detailedStatus = soup.find("div", {"class":"top"}).span.text.strip()
|
|
|
775 |
try:
|
|
|
776 |
displayStatus = soup.find("div",{"class":"a-column a-span12 shipment-status-content"}).span.text.strip()
|
|
|
777 |
except:
|
|
|
778 |
displayStatus = detailedStatus
|
|
|
779 |
print displayStatus
|
|
|
780 |
if detailedStatus.lower().find("delivered")>=0:
|
|
|
781 |
print detailedStatus
|
|
|
782 |
displayStatus = "Delivered"
|
|
|
783 |
status = "Delivered"
|
|
|
784 |
try:
|
|
|
785 |
subOrder["deliveredOn"] = detailedStatus.split("on")[1].strip()
|
|
|
786 |
except:
|
|
|
787 |
pass
|
|
|
788 |
|
|
|
789 |
elif detailedStatus.lower() == 'returned':
|
|
|
790 |
status = 'Cancelled'
|
|
|
791 |
subOrder['status'] = status
|
|
|
792 |
subOrder['detailedStatus'] = displayStatus
|
| 17350 |
amit.gupta |
793 |
self.db.merchantOrder.update({"orderId":orderId}, {"$set":{"trackError":False}})
|
| 16468 |
amit.gupta |
794 |
|
|
|
795 |
except:
|
| 17350 |
amit.gupta |
796 |
self.db.merchantOrder.update({"orderId":orderId}, {"$set":{"trackError":True}})
|
| 16468 |
amit.gupta |
797 |
print "failed to parse", orderId
|
|
|
798 |
traceback.print_exc()
|
|
|
799 |
|
| 14624 |
amit.gupta |
800 |
return subOrder
|
|
|
801 |
|
|
|
802 |
|
|
|
803 |
|
| 16980 |
amit.gupta |
804 |
def parseInfo(self,):
|
|
|
805 |
from pyquery import PyQuery as pq
|
| 16986 |
amit.gupta |
806 |
orders = list(session.query(Orders).filter_by(store_id=self.store_id).filter_by(status='DETAIL_CREATED').group_by(Orders.user_id).all())
|
| 16980 |
amit.gupta |
807 |
try:
|
|
|
808 |
for order in orders:
|
|
|
809 |
try:
|
|
|
810 |
doc = pq(order.rawhtml)
|
|
|
811 |
#a1= " ".join(["" if not div.text else div.text.replace("\t","").replace("\n","").replace(" ", "") for div in pq(doc('article')[-1])('div')])
|
|
|
812 |
lists = doc('ul.displayAddressUL li')
|
| 16986 |
amit.gupta |
813 |
orderInfo = All_user_addresses()
|
| 16980 |
amit.gupta |
814 |
orderInfo.address = lists[-3].text
|
|
|
815 |
orderInfo.user_id = order.user_id
|
| 16986 |
amit.gupta |
816 |
orderInfo.source = 'order'
|
|
|
817 |
#orderInfo.order_id = order.id
|
|
|
818 |
#orderInfo.email = None
|
|
|
819 |
#orderInfo.name = lists[0].text
|
|
|
820 |
#orderInfo.mobile = None
|
| 16980 |
amit.gupta |
821 |
adSplit = lists[-2].text.split(",")
|
|
|
822 |
match = re.match(r"([a-z ]+)([0-9]+)", adSplit[1], re.I)
|
|
|
823 |
if match:
|
|
|
824 |
items = match.groups()
|
| 16986 |
amit.gupta |
825 |
orderInfo.city = adSplit[0].strip()
|
|
|
826 |
orderInfo.pincode = items[1].strip()
|
|
|
827 |
orderInfo.state = items[0].strip().title()
|
| 16980 |
amit.gupta |
828 |
session.commit()
|
|
|
829 |
except:
|
|
|
830 |
session.rollback()
|
|
|
831 |
continue
|
|
|
832 |
finally:
|
|
|
833 |
session.close()
|
| 14608 |
amit.gupta |
834 |
|
| 13927 |
amit.gupta |
835 |
|
|
|
836 |
|
| 13774 |
amit.gupta |
837 |
def main():
|
| 16874 |
amit.gupta |
838 |
store = getStore(1)
|
| 18376 |
amit.gupta |
839 |
#store.parseOrderRawHtml("444444", '123', 14, readSSh('/home/amit/80444.html'), 'https://www.amazon.in/gp/css/summary/edit.html?orderID=402-1449548-9569169')
|
| 18031 |
amit.gupta |
840 |
orders = list(session.query(OrdersRaw).filter_by(status = 'DETAIL_NOT_CREATED_UNKNOWN').filter(OrdersRaw.id > 61071).all())
|
| 18378 |
amit.gupta |
841 |
session.close()
|
| 18377 |
amit.gupta |
842 |
for o in orders:
|
|
|
843 |
try:
|
|
|
844 |
store.trackOrdersForUser(o.id, o.order_url, o.rawhtml)
|
|
|
845 |
finally:
|
|
|
846 |
session.close()
|
| 17631 |
amit.gupta |
847 |
#store.trackOrdersForUser(10466, 'https://www.amazon.in/gp/css/summary/edit.html?orderID=403-7498756-0837158', readSSh('/AmazonTrack/User10466/403-7498756-0837158'))
|
| 18030 |
amit.gupta |
848 |
#store.trackOrdersForUser(46195, 'https://www.amazon.in/gp/css/summary/edit.html?orderID=404-4294022-1187515', readSSh('/home/amit/amazon.html'))
|
| 17231 |
amit.gupta |
849 |
|
|
|
850 |
def getSummaryFile(directory):
|
|
|
851 |
date1 = datetime(2015,1,1)
|
|
|
852 |
finalFile = None
|
|
|
853 |
try:
|
|
|
854 |
for file in os.listdir(directory):
|
|
|
855 |
if file.startswith("orderSummary"):
|
|
|
856 |
date2 = datetime.strptime("2015-" + file.split("orderSummary")[1].split(":")[0], "%Y-%d-%m")
|
|
|
857 |
if date2 > date1:
|
|
|
858 |
date1 = date2
|
|
|
859 |
finalFile=file
|
|
|
860 |
except:
|
|
|
861 |
print "Missing directory"
|
| 17251 |
amit.gupta |
862 |
return finalFile
|
| 17231 |
amit.gupta |
863 |
|
| 15555 |
amit.gupta |
864 |
|
|
|
865 |
def parseDetailNotCreated():
|
|
|
866 |
try:
|
|
|
867 |
store=getStore(1)
|
|
|
868 |
orders = session.query(OrdersRaw).filter_by(status='DETAIL_NOT_CREATED_UNKNOWN').all()
|
| 15558 |
amit.gupta |
869 |
session.close()
|
| 15555 |
amit.gupta |
870 |
for order in orders:
|
|
|
871 |
store.trackOrdersForUser(order.id, order.order_url, order.rawhtml)
|
|
|
872 |
|
|
|
873 |
finally:
|
|
|
874 |
session.close()
|
| 17251 |
amit.gupta |
875 |
|
|
|
876 |
def getDateStringDelivered(dateString='Monday'):
|
| 17254 |
amit.gupta |
877 |
print dateString
|
| 17251 |
amit.gupta |
878 |
if dateString.lower()=='today':
|
|
|
879 |
return date.today()
|
|
|
880 |
if dateString.lower()=='yesterday':
|
|
|
881 |
return date.today() - timedelta(days=1)
|
|
|
882 |
try:
|
|
|
883 |
return datetime.strptime(dateString, '%d-%b-%y')
|
|
|
884 |
except:
|
|
|
885 |
try:
|
|
|
886 |
#get Closest Date from today
|
|
|
887 |
curDate = date.today()
|
|
|
888 |
curTime = datetime(curDate.year, curDate.month, curDate.day)
|
|
|
889 |
curYear = curDate.year
|
|
|
890 |
prevYear = curYear - 1
|
| 17254 |
amit.gupta |
891 |
dateMax = datetime.strptime(dateString + " " + str(curYear), "%A, %d %b %Y")
|
|
|
892 |
dateMin = datetime.strptime(dateString + " " + str(prevYear), "%A, %d %b %Y")
|
| 17251 |
amit.gupta |
893 |
if dateMax <= curTime:
|
|
|
894 |
return dateMax
|
|
|
895 |
else:
|
|
|
896 |
return dateMin
|
|
|
897 |
except:
|
| 17254 |
amit.gupta |
898 |
try:
|
|
|
899 |
days_of_week = ['sunday','monday','tuesday','wednesday',
|
|
|
900 |
'thursday','friday','saturday']
|
|
|
901 |
deltaDays = curDate.isoweekday() - days_of_week.index(dateString.lower())
|
|
|
902 |
if deltaDays <= 0:
|
|
|
903 |
deltaDays= deltaDays + 7
|
|
|
904 |
curDate = curDate - timedelta(days=deltaDays)
|
|
|
905 |
print datetime.strftime(curDate, '%d-%b-%y')
|
|
|
906 |
return curDate
|
|
|
907 |
except:
|
|
|
908 |
print "could not parse"
|
|
|
909 |
return None
|
| 15565 |
amit.gupta |
910 |
|
| 17254 |
amit.gupta |
911 |
def getDateStringArriving(dateString='Thursday'):
|
|
|
912 |
print dateString
|
|
|
913 |
if dateString.lower()=='today':
|
|
|
914 |
return date.today()
|
|
|
915 |
if dateString.lower()=='tomorrow':
|
|
|
916 |
return date.today() + timedelta(days=1)
|
|
|
917 |
try:
|
|
|
918 |
return datetime.strptime(dateString, '%d-%b-%y')
|
|
|
919 |
except:
|
|
|
920 |
try:
|
|
|
921 |
#get Closest Date from today
|
|
|
922 |
curDate = date.today()
|
|
|
923 |
curTime = datetime(curDate.year, curDate.month, curDate.day)
|
|
|
924 |
curYear = curDate.year
|
|
|
925 |
nextYear = curYear + 1
|
|
|
926 |
dateMin = datetime.strptime(dateString + " " + str(curYear), "%A, %d %b %Y")
|
|
|
927 |
dateMax = datetime.strptime(dateString + " " + str(nextYear), "%A, %d %b %Y")
|
|
|
928 |
if dateMin >= curTime:
|
|
|
929 |
return dateMin
|
|
|
930 |
else:
|
|
|
931 |
return dateMax
|
|
|
932 |
except:
|
|
|
933 |
try:
|
|
|
934 |
days_of_week = ['sunday','monday','tuesday','wednesday',
|
|
|
935 |
'thursday','friday','saturday']
|
|
|
936 |
deltaDays = days_of_week.index(dateString.lower()) - curDate.isoweekday()
|
|
|
937 |
if deltaDays < 0:
|
|
|
938 |
deltaDays= deltaDays + 7
|
|
|
939 |
curDate = curDate + timedelta(days=deltaDays)
|
|
|
940 |
return curDate
|
|
|
941 |
except:
|
|
|
942 |
print "Could not parse"
|
|
|
943 |
return None
|
|
|
944 |
|
| 18028 |
amit.gupta |
945 |
def main1():
|
|
|
946 |
store = getStore(1)
|
|
|
947 |
for merchantOrder in store.db.merchantOrder.find({"subOrders":{"$elemMatch":{"cashBackStatus":"Not Applicable", "cashBackPercentage":{"$gt":0}}}}):
|
|
|
948 |
mo = obj(merchantOrder)
|
|
|
949 |
for subOrder in mo.subOrders:
|
|
|
950 |
subOrder.closed=False
|
|
|
951 |
print "orderId", mo.orderId
|
|
|
952 |
store.populateDerivedFields(mo, False)
|
|
|
953 |
store.db.merchantOrder.update({"orderId":mo.orderId}, {"$set":todict(mo)})
|
|
|
954 |
break
|
|
|
955 |
|
|
|
956 |
|
| 15565 |
amit.gupta |
957 |
def parseOrderNotCreated():
|
|
|
958 |
try:
|
|
|
959 |
store=getStore(1)
|
|
|
960 |
orders = session.query(OrdersRaw).filter_by(status='ORDER_NOT_CREATED_UNKNOWN').all()
|
|
|
961 |
session.close()
|
|
|
962 |
for order in orders:
|
| 15567 |
amit.gupta |
963 |
result = store.parseOrderRawHtml(order.id, order.sub_tag, order.user_id, order.rawhtml, order.order_url)['result']
|
|
|
964 |
order1 = session.query(OrdersRaw).filter_by(id=order.id).first()
|
|
|
965 |
order1.status = result
|
|
|
966 |
session.commit()
|
| 15565 |
amit.gupta |
967 |
finally:
|
|
|
968 |
session.close()
|
| 15555 |
amit.gupta |
969 |
|
| 13774 |
amit.gupta |
970 |
if __name__ == '__main__':
|
| 17599 |
amit.gupta |
971 |
# readSSh("/AmazonTrack/User2942/402-2467356-7564367")
|
|
|
972 |
# readSSh("/AmazonTrack/User10466/orderSummary18-11:21:32:36")
|
| 18156 |
amit.gupta |
973 |
# readSSh("/AmazonTrack/User5525/171-0333104-6169933")
|
| 18159 |
amit.gupta |
974 |
main()
|
|
|
975 |
#store=getStore(1)
|
|
|
976 |
#store.trackOrdersForUser(5525, "https://www.amazon.in/gp/css/summary/edit.html?orderID=171-0333104-6169933", readSSh("/AmazonTrack/User5525/171-0333104-6169933"))
|