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