| 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
|
| 14650 |
amit.gupta |
9 |
from datetime import datetime, timedelta
|
|
|
10 |
from dtr.dao import Order, SubOrder, AmazonAffiliateInfo
|
| 14464 |
amit.gupta |
11 |
from dtr.main import getStore, Store as MStore, ParseException, getBrowserObject, \
|
| 14624 |
amit.gupta |
12 |
ungzipResponse, tprint
|
| 14650 |
amit.gupta |
13 |
from dtr.sources.flipkart import todict, AFF_REPORT_URL
|
| 14749 |
amit.gupta |
14 |
from dtr.utils.utils import fetchResponseUsingProxy
|
| 14162 |
amit.gupta |
15 |
from paramiko import sftp
|
|
|
16 |
from paramiko.client import SSHClient
|
|
|
17 |
from paramiko.sftp_client import SFTPClient
|
| 14650 |
amit.gupta |
18 |
import base64
|
|
|
19 |
import gzip
|
| 14624 |
amit.gupta |
20 |
import mechanize
|
| 14285 |
amit.gupta |
21 |
import os.path
|
| 14162 |
amit.gupta |
22 |
import paramiko
|
| 13774 |
amit.gupta |
23 |
import re
|
| 14033 |
amit.gupta |
24 |
import time
|
| 13809 |
amit.gupta |
25 |
import traceback
|
| 14650 |
amit.gupta |
26 |
import urllib2
|
| 15346 |
amit.gupta |
27 |
from dtr.storage.Mongo import getDealRank
|
| 13774 |
amit.gupta |
28 |
|
|
|
29 |
ORDER_REDIRECT_URL = 'https://www.amazon.in/gp/css/summary/edit.html?orderID=%s'
|
| 13810 |
amit.gupta |
30 |
ORDER_SUCCESS_URL = 'https://www.amazon.in/gp/buy/spc/handlers/static-submit-decoupled.html'
|
| 13823 |
amit.gupta |
31 |
THANKYOU_URL = 'https://www.amazon.in/gp/buy/thankyou/handlers/display.html'
|
| 14624 |
amit.gupta |
32 |
AMAZON_AFF_URL = 'https://assoc-datafeeds-eu.amazon.com/datafeed/listReports'
|
| 14650 |
amit.gupta |
33 |
AMAZON_AFF_FILE_URL = 'https://assoc-datafeeds-eu.amazon.com/datafeed/getReport?filename=saholic-21-orders-report-%s.tsv.gz'
|
| 13774 |
amit.gupta |
34 |
class Store(MStore):
|
| 13821 |
amit.gupta |
35 |
|
| 14032 |
amit.gupta |
36 |
orderStatusRegexMap = { MStore.ORDER_PLACED : ['ordered from', 'not yet dispatched','dispatching now', 'preparing for dispatch'],
|
| 14064 |
amit.gupta |
37 |
MStore.ORDER_SHIPPED : ['dispatched on','dispatched', 'on the way', 'out for delivery', 'Out for delivery'],
|
| 14032 |
amit.gupta |
38 |
MStore.ORDER_CANCELLED : ['return complete', 'refunded', 'cancelled'],
|
|
|
39 |
MStore.ORDER_DELIVERED : ['delivered']
|
| 13821 |
amit.gupta |
40 |
}
|
| 13774 |
amit.gupta |
41 |
|
|
|
42 |
def __init__(self,store_id):
|
|
|
43 |
super(Store, self).__init__(store_id)
|
|
|
44 |
|
|
|
45 |
def getName(self):
|
| 14749 |
amit.gupta |
46 |
return "amazon"
|
| 13774 |
amit.gupta |
47 |
|
| 14945 |
amit.gupta |
48 |
def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl, track=False):
|
| 14958 |
amit.gupta |
49 |
parseString = "Tracking" if track else "Transacted"
|
|
|
50 |
print parseString, "Order Id to be parsed is :", orderId
|
| 13796 |
amit.gupta |
51 |
resp = {}
|
| 14813 |
amit.gupta |
52 |
resp['result'] = 'ORDER_NOT_CREATED'
|
| 13821 |
amit.gupta |
53 |
if ORDER_SUCCESS_URL in orderSuccessUrl or THANKYOU_URL in orderSuccessUrl:
|
| 13774 |
amit.gupta |
54 |
try:
|
|
|
55 |
soup = BeautifulSoup(rawHtml)
|
| 14608 |
amit.gupta |
56 |
try:
|
|
|
57 |
orderUrl = soup.find('div', {"id":"thank-you-box-wrapper"}).div.findAll('div', recursive=False)[1].a['href']
|
|
|
58 |
merchantOrderId = re.findall(r'.*&oid=(.*)&?.*?', orderUrl)[0]
|
|
|
59 |
except:
|
|
|
60 |
merchantOrderId = soup.find(id="orders-list").div.span.b.text
|
| 14699 |
amit.gupta |
61 |
order = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl, True)
|
| 14972 |
amit.gupta |
62 |
order.orderTrackingUrl = ORDER_REDIRECT_URL % (merchantOrderId)
|
|
|
63 |
order.orderSuccessUrl = orderSuccessUrl
|
| 14211 |
amit.gupta |
64 |
order.merchantOrderId = merchantOrderId
|
| 14291 |
amit.gupta |
65 |
order.requireDetail = True
|
| 14698 |
amit.gupta |
66 |
order.status = 'html_required'
|
| 14297 |
amit.gupta |
67 |
order.closed = None
|
| 14312 |
amit.gupta |
68 |
if self._saveToOrder(todict(order)):
|
|
|
69 |
resp['result'] = 'ORDER_CREATED'
|
|
|
70 |
resp["url"] = ORDER_REDIRECT_URL % (merchantOrderId)
|
|
|
71 |
resp["htmlRequired"] = True
|
|
|
72 |
resp['orderId'] = orderId
|
|
|
73 |
else:
|
|
|
74 |
resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
|
|
|
75 |
|
| 13774 |
amit.gupta |
76 |
except:
|
| 14813 |
amit.gupta |
77 |
#Write all cases here for Order Not created Known
|
| 14809 |
amit.gupta |
78 |
try:
|
| 14815 |
amit.gupta |
79 |
if 'Securely redirecting you' in soup.h3.text.strip():
|
| 14813 |
amit.gupta |
80 |
resp['result'] = 'ORDER_NOT_CREATED_KNOWN'
|
| 14809 |
amit.gupta |
81 |
else:
|
| 14813 |
amit.gupta |
82 |
raise
|
| 14809 |
amit.gupta |
83 |
except:
|
| 14814 |
amit.gupta |
84 |
try:
|
| 14815 |
amit.gupta |
85 |
if soup.h1.text.strip() in ['This is a duplicate order', 'There was a problem with your payment.']:
|
| 14814 |
amit.gupta |
86 |
resp['result'] = 'ORDER_NOT_CREATED_KNOWN'
|
|
|
87 |
else:
|
|
|
88 |
raise
|
|
|
89 |
except:
|
| 15046 |
amit.gupta |
90 |
try:
|
|
|
91 |
if soup.h2.text.strip() == 'Web page not available':
|
|
|
92 |
resp['result'] = 'ORDER_NOT_CREATED_KNOWN'
|
|
|
93 |
else:
|
|
|
94 |
raise
|
|
|
95 |
except:
|
|
|
96 |
resp['result'] = 'ORDER_NOT_CREATED_UNKNOWN'
|
| 13774 |
amit.gupta |
97 |
else:
|
| 13781 |
amit.gupta |
98 |
try:
|
| 14722 |
amit.gupta |
99 |
mo = self.db.merchantOrder.find_one({"orderId":orderId})
|
|
|
100 |
if mo is not None:
|
| 14749 |
amit.gupta |
101 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl, False)
|
| 14722 |
amit.gupta |
102 |
merchantOrder.createdOn = mo.get("createdOn")
|
|
|
103 |
merchantOrder.createdOnInt = mo.get("createdOnInt")
|
|
|
104 |
else:
|
| 14945 |
amit.gupta |
105 |
print "Could not find amazon order with order Id", orderId
|
| 14749 |
amit.gupta |
106 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
|
| 14464 |
amit.gupta |
107 |
soup = BeautifulSoup(rawHtml)
|
|
|
108 |
try:
|
| 14961 |
amit.gupta |
109 |
self.parseNewStlye(merchantOrder, soup)
|
| 15046 |
amit.gupta |
110 |
resp['result'] = 'DETAIL_CREATED'
|
| 14464 |
amit.gupta |
111 |
except:
|
| 14545 |
amit.gupta |
112 |
try:
|
| 14566 |
amit.gupta |
113 |
traceback.print_exc()
|
| 14961 |
amit.gupta |
114 |
self.parseOldStlye(merchantOrder, soup)
|
| 15046 |
amit.gupta |
115 |
resp['result'] = 'DETAIL_CREATED'
|
| 14545 |
amit.gupta |
116 |
except:
|
| 14566 |
amit.gupta |
117 |
traceback.print_exc()
|
| 15056 |
amit.gupta |
118 |
try:
|
|
|
119 |
self.parseCancelled(merchantOrder, soup)
|
|
|
120 |
resp['result'] = 'ORDER_CANCELLED'
|
|
|
121 |
except:
|
| 15059 |
amit.gupta |
122 |
try:
|
|
|
123 |
if soup.h1.span.text=="Account":
|
|
|
124 |
resp['result'] = 'DETAIL_NOT_CREATED_KNOWN'
|
|
|
125 |
else:
|
|
|
126 |
raise
|
|
|
127 |
except:
|
|
|
128 |
if soup.find(id="ap_signin_pagelet_title").h1.text.strip()=="Sign In":
|
|
|
129 |
resp['result'] = 'DETAIL_NOT_CREATED_KNOWN'
|
|
|
130 |
else:
|
|
|
131 |
raise
|
| 13781 |
amit.gupta |
132 |
except:
|
| 14813 |
amit.gupta |
133 |
order = self.db.merchantOrder.find_one({"orderId":orderId})
|
|
|
134 |
if order is not None:
|
|
|
135 |
self.db.merchantOrder.update({"orderId":orderId}, {"$set":{"status":"parse_failed"}})
|
|
|
136 |
print "Error occurred"
|
| 15046 |
amit.gupta |
137 |
resp['result'] = 'DETAIL_NOT_CREATED_UNKNOWN'
|
| 14813 |
amit.gupta |
138 |
traceback.print_exc()
|
| 15046 |
amit.gupta |
139 |
return resp
|
| 13774 |
amit.gupta |
140 |
|
| 13868 |
amit.gupta |
141 |
#This should be exposed from api for specific sources
|
|
|
142 |
def scrapeStoreOrders(self):
|
| 14624 |
amit.gupta |
143 |
orders = self.db.merchantOrder.find({"storeId":1, "closed":False, "subOrders.closed":False, "subOrders.trackingUrl":{"$exists":True}})
|
|
|
144 |
for merchantOrder in orders:
|
| 14981 |
amit.gupta |
145 |
executeBulk = False
|
| 14624 |
amit.gupta |
146 |
try:
|
|
|
147 |
bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
|
|
148 |
closed = True
|
|
|
149 |
map1 = {}
|
|
|
150 |
for subOrder in merchantOrder.get("subOrders"):
|
|
|
151 |
if subOrder.get("closed"):
|
|
|
152 |
continue
|
|
|
153 |
elif subOrder.get("trackingUrl") is None:
|
|
|
154 |
closed = False
|
|
|
155 |
continue
|
| 14981 |
amit.gupta |
156 |
executeBulk = True
|
| 14624 |
amit.gupta |
157 |
findMap = {"orderId":merchantOrder.get("orderId"), "subOrders.merchantSubOrderId":subOrder.get("merchantSubOrderId")}
|
|
|
158 |
trackingUrl = subOrder.get("trackingUrl")
|
|
|
159 |
if not map1.has_key(trackingUrl):
|
| 14749 |
amit.gupta |
160 |
map1[trackingUrl] = self.parseTrackingUrl(trackingUrl)
|
| 14624 |
amit.gupta |
161 |
newOrder = map1.get(trackingUrl)
|
|
|
162 |
newOrder['cashBackStatus'] = subOrder.get('cashBackStatus')
|
|
|
163 |
updateMap = self.getUpdateMap(newOrder)
|
|
|
164 |
print findMap, "\n", updateMap
|
|
|
165 |
bulk.find(findMap).update({'$set' : updateMap})
|
|
|
166 |
closed = closed and newOrder['closed']
|
| 14981 |
amit.gupta |
167 |
if executeBulk:
|
| 14697 |
amit.gupta |
168 |
bulk.find({"orderId":merchantOrder.get("orderId")}).update({"$set":{"closed":closed, "parseError":False}})
|
| 14981 |
amit.gupta |
169 |
bulk.execute()
|
| 14624 |
amit.gupta |
170 |
except:
|
| 14847 |
amit.gupta |
171 |
tprint("Could not update " + str(merchantOrder['orderId']) + " For store " + self.getName())
|
| 14692 |
amit.gupta |
172 |
self.db.merchantOrder.update({"orderId":merchantOrder['orderId']}, {"$set":{"parseError":True}})
|
| 14624 |
amit.gupta |
173 |
traceback.print_exc()
|
|
|
174 |
|
| 14608 |
amit.gupta |
175 |
|
|
|
176 |
|
| 14771 |
amit.gupta |
177 |
def parserest(self, soup):
|
|
|
178 |
print "Hi"
|
|
|
179 |
if soup.find('h1'):
|
|
|
180 |
print "OK"
|
| 14608 |
amit.gupta |
181 |
|
| 14464 |
amit.gupta |
182 |
def parseOldStlye(self, merchantOrder, soup):
|
|
|
183 |
merchantOrder.orderTrackingUrl = merchantOrder.orderSuccessUrl
|
|
|
184 |
table = soup.body.findAll("table", recursive=False)[1]
|
|
|
185 |
#print table
|
|
|
186 |
tables = table.tr.td.findAll("table", recursive=False)
|
|
|
187 |
for tr in tables[2].findAll("tr"):
|
|
|
188 |
boldElement = tr.td.b
|
|
|
189 |
if "Order Placed" in str(boldElement):
|
|
|
190 |
merchantOrder.placedOn = boldElement.next_sibling.strip()
|
|
|
191 |
if "order number" in str(boldElement):
|
|
|
192 |
merchantOrder.merchantOrderId = boldElement.next_sibling.strip()
|
|
|
193 |
if "Order Total" in str(boldElement):
|
|
|
194 |
merchantOrder.paidAmount = int(float(boldElement.find('span').contents[-1].replace(',','')))
|
|
|
195 |
anchors = table.tr.td.findAll("a", recursive=False)
|
|
|
196 |
paymentAnchor = anchors.pop(-1)
|
|
|
197 |
|
|
|
198 |
count = 0
|
|
|
199 |
subOrders = []
|
|
|
200 |
merchantOrder.subOrders = subOrders
|
|
|
201 |
counter = 0
|
|
|
202 |
for anchor in anchors:
|
|
|
203 |
count += 1
|
|
|
204 |
tab = anchor.next_sibling
|
|
|
205 |
status = MStore.ORDER_PLACED
|
|
|
206 |
subStr = "Delivery #" + str(count) + ":"
|
|
|
207 |
if subStr in tab.find("b").text:
|
|
|
208 |
detailedStatus = tab.find("b").text.replace(subStr, '').strip()
|
|
|
209 |
|
|
|
210 |
tab = tab.next_sibling.next_sibling
|
|
|
211 |
trs = tab.find("table").find('tbody').findAll("tr", recursive = False)
|
|
|
212 |
|
|
|
213 |
estimatedDelivery = trs[0].td.find("b").next_sibling.strip()
|
|
|
214 |
|
|
|
215 |
orderItemTrs = trs[1].findAll("td", recursive=False)[1].table.tbody.findAll("tr", recursive = False)
|
|
|
216 |
i = -1
|
|
|
217 |
for orderItemTr in orderItemTrs:
|
|
|
218 |
i += 1
|
|
|
219 |
if i%2 == 0:
|
|
|
220 |
continue
|
|
|
221 |
counter += 1
|
|
|
222 |
quantity = int(re.findall(r'\d+', orderItemTr.td.contents[0])[0])
|
|
|
223 |
|
|
|
224 |
productUrl = orderItemTr.td.contents[1].a["href"]
|
|
|
225 |
productTitle = orderItemTr.td.contents[1].a.text
|
|
|
226 |
|
|
|
227 |
unitPrice = int(float(orderItemTr.findAll('td')[1].span.text.replace('Rs. ','').replace(',','')))
|
|
|
228 |
|
|
|
229 |
|
|
|
230 |
subOrder = SubOrder(productTitle, productUrl, merchantOrder.placedOn, unitPrice*quantity, status, quantity)
|
|
|
231 |
subOrder.merchantSubOrderId = str(counter) + " of " + merchantOrder.merchantOrderId
|
|
|
232 |
subOrder.estimatedDeliveryDate = estimatedDelivery
|
| 14722 |
amit.gupta |
233 |
estDlvyTime = datetime.strptime(estimatedDelivery.split('-')[0].strip(), "%A %d %B %Y")
|
|
|
234 |
createdOn = datetime.fromtimestamp(merchantOrder.createdOnInt)
|
|
|
235 |
subOrder.trackAfter = int(time.mktime(max(estDlvyTime-timedelta(days=4),createdOn + timedelta(days=3)).timetuple()))
|
| 14464 |
amit.gupta |
236 |
subOrder.productCode = productUrl.split('/')[5]
|
|
|
237 |
subOrder.detailedStatus = detailedStatus
|
|
|
238 |
(cashbackAmount, percentage) = self.getCashbackAmount(subOrder.productCode, unitPrice*quantity)
|
| 15346 |
amit.gupta |
239 |
dealRank = getDealRank(subOrder.productCode, self.store_id, merchantOrder.userId)
|
|
|
240 |
subOrder.dealRank = dealRank.get('rank')
|
|
|
241 |
subOrder.rankDesc = dealRank.get('description')
|
| 14464 |
amit.gupta |
242 |
cashbackStatus = Store.CB_PENDING
|
|
|
243 |
if cashbackAmount <= 0:
|
|
|
244 |
cashbackStatus = Store.CB_NA
|
|
|
245 |
subOrder.cashBackStatus = cashbackStatus
|
|
|
246 |
subOrder.cashBackAmount = cashbackAmount
|
|
|
247 |
if percentage > 0:
|
|
|
248 |
subOrder.cashBackPercentage = percentage
|
|
|
249 |
subOrders.append(subOrder)
|
|
|
250 |
priceList = paymentAnchor.next_sibling.next_sibling.next_sibling.table.table.tbody.tbody.tbody.findAll('tr', recursive=False)
|
|
|
251 |
totalAmount = 0
|
|
|
252 |
grandAmount = 0
|
|
|
253 |
for price in priceList:
|
|
|
254 |
labelTd = price.td
|
|
|
255 |
if 'Subtotal:' in labelTd.text:
|
|
|
256 |
totalAmount += int(float(labelTd.next_sibling.next_sibling.find('span').contents[-1].replace(',','')))
|
|
|
257 |
elif 'Grand Total:' in labelTd.text:
|
|
|
258 |
grandAmount += int(float(labelTd.next_sibling.next_sibling.find('span').contents[-1].replace(',','')))
|
|
|
259 |
if grandAmount < totalAmount:
|
|
|
260 |
diff = totalAmount - grandAmount
|
|
|
261 |
for subOrder in merchantOrder.subOrders:
|
|
|
262 |
subOrder.amountPaid -= int(diff*(1-subOrder.amountPaid/totalAmount))
|
| 14698 |
amit.gupta |
263 |
merchantOrder.status='success'
|
| 14464 |
amit.gupta |
264 |
self._updateToOrder(todict(merchantOrder))
|
|
|
265 |
|
|
|
266 |
def parseNewStlye(self, merchantOrder, soup):
|
|
|
267 |
merchantOrder.orderTrackingUrl = merchantOrder.orderSuccessUrl
|
|
|
268 |
orderDetailsContainer = soup.body.find(id="orderDetails")
|
| 14566 |
amit.gupta |
269 |
divAfterH1 = orderDetailsContainer.h1.next_sibling.next_sibling
|
|
|
270 |
orderLeftDiv = divAfterH1.div
|
| 14464 |
amit.gupta |
271 |
placedOnSpan = orderLeftDiv.find("span", {'class':'order-date-invoice-item'})
|
|
|
272 |
merchantOrder.placedOn =placedOnSpan.text.split('Ordered on')[1].strip()
|
|
|
273 |
merchantOrder.merchantOrderId = placedOnSpan.next_sibling.next_sibling.text.split('Order#')[1].strip()
|
| 14566 |
amit.gupta |
274 |
priceBox = divAfterH1.next_sibling.next_sibling.next_sibling.next_sibling.find("div", {"class":"a-box-inner"}).div.div.findAll('div', recursive=False)[-1]
|
| 14464 |
amit.gupta |
275 |
priceRows = priceBox.findAll('div', {'class':'a-row'})
|
|
|
276 |
subTotal = 0
|
| 14566 |
amit.gupta |
277 |
shippingPrice = 0
|
| 14464 |
amit.gupta |
278 |
promoApplied = 0
|
|
|
279 |
for priceRow in priceRows:
|
|
|
280 |
if "Item(s) Subtotal:" in str(priceRow):
|
|
|
281 |
subTotal = int(float(priceRow.div.next_sibling.next_sibling.span.span.text.replace('Rs.','').replace(',', '')))
|
|
|
282 |
elif "Shipping:" in str(priceRow):
|
|
|
283 |
shippingPrice = int(float(priceRow.div.next_sibling.next_sibling.span.span.text.replace('Rs.','').replace(',', '')))
|
|
|
284 |
elif "Grand Total:" in str(priceRow):
|
|
|
285 |
grandPrice = int(float(priceRow.div.next_sibling.next_sibling.span.span.text.replace('Rs.','').replace(',', '')))
|
|
|
286 |
merchantOrder.paidAmount = grandPrice
|
|
|
287 |
elif "Total:" in str(priceRow):
|
|
|
288 |
totalPrice = int(float(priceRow.div.next_sibling.next_sibling.span.span.text.replace('Rs.','').replace(',', '')))
|
|
|
289 |
elif "Promotion Applied:" in str(priceRow):
|
|
|
290 |
promoApplied += int(float(priceRow.div.next_sibling.next_sibling.span.span.text.replace('Rs.','').replace(',', '')))
|
|
|
291 |
totalPaid = subTotal
|
|
|
292 |
if promoApplied > 0:
|
|
|
293 |
totalPaid -= promoApplied
|
|
|
294 |
if shippingPrice <= promoApplied:
|
|
|
295 |
totalPaid += shippingPrice
|
|
|
296 |
|
|
|
297 |
shipmentDivs = orderDetailsContainer.find('div', {'class':'a-box shipment'}).findAll('div', recursive = False)
|
|
|
298 |
subOrders = []
|
|
|
299 |
merchantOrder.subOrders = subOrders
|
|
|
300 |
i=1
|
|
|
301 |
for shipmentDiv in shipmentDivs:
|
|
|
302 |
innerBoxes = shipmentDiv.findAll('div', recursive = False)
|
|
|
303 |
statusDiv = innerBoxes[0]
|
|
|
304 |
subOrderStatus = statusDiv.div.span.text.strip()
|
| 14566 |
amit.gupta |
305 |
deliverySpan = statusDiv.div.div.find_next_sibling('div').span
|
| 14464 |
amit.gupta |
306 |
productDivs = innerBoxes[-1].div.div.div.findAll('div', recursive=False)
|
|
|
307 |
subOrders = []
|
|
|
308 |
merchantOrder.subOrders = subOrders
|
|
|
309 |
for i, productDiv in enumerate(productDivs):
|
|
|
310 |
i +=1
|
|
|
311 |
imgDiv = productDiv.div.div
|
|
|
312 |
detailDiv = imgDiv.find_next_sibling('div')
|
|
|
313 |
detailDivs = detailDiv.findAll('div', recursive=False)
|
|
|
314 |
arr = detailDivs[0].a.text.strip().split(" of ", 1)
|
| 14465 |
amit.gupta |
315 |
(productTitle, quantity) = (arr[-1], (1 if len(arr)==1 else int(arr[0])) )
|
| 14820 |
amit.gupta |
316 |
try:
|
|
|
317 |
unitPrice = int(float(detailDivs[2].span.text.replace('Rs. ','').replace(',','')))
|
|
|
318 |
except:
|
|
|
319 |
unitPrice = int(float(detailDivs[3].span.text.replace('Rs. ','').replace(',','')))
|
| 14464 |
amit.gupta |
320 |
amountPaid = int((unitPrice*quantity*totalPaid)/subTotal)
|
|
|
321 |
productUrl = "http://www.amazon.in" + detailDivs[0].a.get('href')
|
|
|
322 |
subOrder = SubOrder(productTitle, productUrl, merchantOrder.placedOn, amountPaid, MStore.ORDER_PLACED, quantity)
|
|
|
323 |
subOrder.productCode = productUrl.split('/')[5]
|
|
|
324 |
subOrder.unitPrice = unitPrice
|
| 14566 |
amit.gupta |
325 |
subOrder.merchantSubOrderId = str(i) + " of " + merchantOrder.merchantOrderId
|
| 14722 |
amit.gupta |
326 |
estDlvyTime = datetime.now()
|
| 14566 |
amit.gupta |
327 |
if deliverySpan is not None:
|
| 14756 |
amit.gupta |
328 |
try:
|
|
|
329 |
subOrder.estimatedDeliveryDate = deliverySpan.span.text.strip()
|
|
|
330 |
estDate = subOrder.estimatedDeliveryDate.split("-")[0].strip()
|
|
|
331 |
subOrder.estimatedDeliveryInt = int(time.mktime((datetime.strptime(estDate, "%A %d %B %Y")).timetuple()))
|
|
|
332 |
estDlvyTime = datetime.strptime(estDate, "%A %d %B %Y")
|
|
|
333 |
except:
|
|
|
334 |
subOrder.estimatedDeliveryDate = "Not available"
|
| 14722 |
amit.gupta |
335 |
createdOn = datetime.fromtimestamp(merchantOrder.createdOnInt)
|
| 14756 |
amit.gupta |
336 |
subOrder.trackAfter = int(time.mktime(max(estDlvyTime-timedelta(days=4),createdOn + timedelta(days=3)).timetuple()))
|
| 14464 |
amit.gupta |
337 |
subOrder.detailedStatus = subOrderStatus
|
|
|
338 |
subOrder.deliveryCharges = shippingPrice
|
| 14466 |
amit.gupta |
339 |
subOrder.imgUrl = imgDiv.img["src"]
|
| 14464 |
amit.gupta |
340 |
(cashbackAmount, percentage) = self.getCashbackAmount(subOrder.productCode, amountPaid)
|
| 15346 |
amit.gupta |
341 |
dealRank = getDealRank(subOrder.productCode, self.store_id, merchantOrder.userId)
|
|
|
342 |
subOrder.dealRank = dealRank.get('rank')
|
|
|
343 |
subOrder.rankDesc = dealRank.get('description')
|
| 14464 |
amit.gupta |
344 |
cashbackStatus = Store.CB_PENDING
|
|
|
345 |
if cashbackAmount <= 0:
|
|
|
346 |
cashbackStatus = Store.CB_NA
|
|
|
347 |
subOrder.cashBackStatus = cashbackStatus
|
|
|
348 |
subOrder.cashBackAmount = cashbackAmount
|
|
|
349 |
if percentage > 0:
|
|
|
350 |
subOrder.cashBackPercentage = percentage
|
|
|
351 |
subOrders.append(subOrder)
|
| 14698 |
amit.gupta |
352 |
merchantOrder.status='success'
|
| 14464 |
amit.gupta |
353 |
self._updateToOrder(todict(merchantOrder))
|
| 14545 |
amit.gupta |
354 |
|
|
|
355 |
def parseCancelled(self, merchantOrder,soup):
|
| 14722 |
amit.gupta |
356 |
try:
|
|
|
357 |
fonts = soup.body.findAll("table", recursive=False)[1].findAll("font")
|
|
|
358 |
if fonts[0].text == "Important Message":
|
|
|
359 |
if fonts[1].text=="This order has been cancelled.":
|
|
|
360 |
merchantOrder.closed = True
|
|
|
361 |
merchantOrder.status = "cancelled"
|
|
|
362 |
merchantOrder.requireDetail = False
|
|
|
363 |
self._updateToOrder(todict(merchantOrder))
|
|
|
364 |
return
|
|
|
365 |
else:
|
|
|
366 |
raise ParseException("parseCancelled", "Found detailed status" + fonts[1].text)
|
| 14545 |
amit.gupta |
367 |
else:
|
|
|
368 |
raise ParseException("parseCancelled", "Found detailed status" + fonts[1].text)
|
| 14722 |
amit.gupta |
369 |
except:
|
| 14549 |
amit.gupta |
370 |
orderDetails = soup.body.find(id="orderDetails")
|
|
|
371 |
if orderDetails is not None and orderDetails.h4.text == "This order has been cancelled.":
|
|
|
372 |
merchantOrder.closed = True
|
| 14698 |
amit.gupta |
373 |
merchantOrder.status = "cancelled"
|
| 14549 |
amit.gupta |
374 |
merchantOrder.requireDetail = False
|
|
|
375 |
self._updateToOrder(todict(merchantOrder))
|
|
|
376 |
else:
|
|
|
377 |
raise ParseException("parseCancelled", "Found detailed status" + fonts[1].text)
|
| 14464 |
amit.gupta |
378 |
|
| 13868 |
amit.gupta |
379 |
def getTrackingUrls(self, userId):
|
| 14074 |
amit.gupta |
380 |
|
|
|
381 |
missingOrderUrls = []
|
|
|
382 |
missingOrders = self._getMissingOrders({'userId':userId})
|
|
|
383 |
for missingOrder in missingOrders:
|
|
|
384 |
missingOrderUrls.append(ORDER_REDIRECT_URL%(missingOrder['merchantOrderId']))
|
| 14683 |
amit.gupta |
385 |
orders = self._getActiveOrders({'userId':userId, "subOrders.trackingUrl":{"$exists":False} })
|
| 13882 |
amit.gupta |
386 |
count = len(orders)
|
| 13879 |
amit.gupta |
387 |
print "count", count
|
| 14948 |
amit.gupta |
388 |
print "Missing Urls"
|
|
|
389 |
print "*************"
|
|
|
390 |
print missingOrderUrls
|
| 13868 |
amit.gupta |
391 |
if count > 0:
|
| 14684 |
amit.gupta |
392 |
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 |
393 |
else:
|
| 14074 |
amit.gupta |
394 |
return missingOrderUrls
|
| 13927 |
amit.gupta |
395 |
|
|
|
396 |
def trackOrdersForUser(self, userId, url, rawHtml):
|
| 14985 |
amit.gupta |
397 |
directory = "/AmazonTrack/User" + str(userId)
|
| 14285 |
amit.gupta |
398 |
if not os.path.exists(directory):
|
|
|
399 |
os.makedirs(directory)
|
| 14173 |
amit.gupta |
400 |
|
| 14945 |
amit.gupta |
401 |
|
| 13995 |
amit.gupta |
402 |
try:
|
|
|
403 |
searchMap = {'userId':userId}
|
|
|
404 |
collectionMap = {'merchantOrderId':1}
|
|
|
405 |
activeOrders = self._getActiveOrders(searchMap, collectionMap)
|
| 14033 |
amit.gupta |
406 |
datetimeNow = datetime.now()
|
|
|
407 |
timestamp = int(time.mktime(datetimeNow.timetuple()))
|
| 14009 |
amit.gupta |
408 |
print "url----------------", url
|
| 14008 |
amit.gupta |
409 |
|
| 14320 |
amit.gupta |
410 |
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 |
411 |
if url == 'https://www.amazon.in/gp/css/order-history':
|
|
|
412 |
filename = directory + "/orderSummary" + datetime.strftime(datetime.now(), '%d-%m:%H:%M:%S')
|
|
|
413 |
else:
|
|
|
414 |
filename = directory + "/cancelledSummary" + datetime.strftime(datetime.now(), '%d-%m:%H:%M:%S')
|
|
|
415 |
f = open(filename,'w')
|
|
|
416 |
f.write(rawHtml) # python will convert \n to os.linesep
|
|
|
417 |
f.close() # you can omit in most cases as the destructor will call if
|
| 13995 |
amit.gupta |
418 |
soup = BeautifulSoup(rawHtml)
|
|
|
419 |
allOrders = soup.find(id="ordersContainer").findAll('div', {'class':'a-box-group a-spacing-base order'})
|
|
|
420 |
bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
|
|
421 |
for activeOrder in activeOrders:
|
|
|
422 |
for orderEle in allOrders:
|
|
|
423 |
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'})
|
|
|
424 |
merchantOrderId = orderdiv.find('span', {'class':'a-color-secondary value'}).text.strip()
|
|
|
425 |
if merchantOrderId==activeOrder['merchantOrderId']:
|
|
|
426 |
closed = True
|
|
|
427 |
shipments = orderEle.findAll('div',{'class':re.compile('.*?a-box.*?')}, recursive=False)
|
|
|
428 |
shipments.pop(0)
|
|
|
429 |
for shipment in shipments:
|
|
|
430 |
shipdiv = shipment.find('div', {'class':'a-box-inner'})
|
| 14050 |
amit.gupta |
431 |
sdivs = shipment.div.div.findAll('div', recursive=False)
|
| 14065 |
amit.gupta |
432 |
orderStatus = sdivs[0].span.text.strip()
|
| 14050 |
amit.gupta |
433 |
status = self._getStatusFromDetailedStatus(orderStatus)
|
|
|
434 |
if status == MStore.ORDER_DELIVERED:
|
| 14299 |
amit.gupta |
435 |
deliveredOn = sdivs[0].findAll('span')[-1].text.strip()
|
| 14962 |
amit.gupta |
436 |
try:
|
|
|
437 |
deliveredOn = deliveredOn.split(":")[1].strip()
|
|
|
438 |
except:
|
|
|
439 |
deliveredOn = ""
|
| 14335 |
amit.gupta |
440 |
deliveryestimatespan = sdivs[0].find('span', {'class':'a-color-success'})
|
|
|
441 |
deliveryEstimate = None
|
|
|
442 |
if deliveryestimatespan is not None:
|
|
|
443 |
deliveryEstimate = deliveryestimatespan.find('span', {'class':'a-text-bold'}).text.strip()
|
|
|
444 |
productDivs = shipdiv.find('div', {'class':re.compile('.*?a-spacing-top-medium.*?')}).find('div', {'class':'a-row'}).findAll('div', recursive=False)
|
| 13995 |
amit.gupta |
445 |
trackingUrl = None
|
|
|
446 |
for buttonDiv in shipdiv.findAll('span', {'class':'a-button-inner'}):
|
|
|
447 |
if buttonDiv.find('a').text.strip()=='Track package':
|
|
|
448 |
trackingUrl = buttonDiv.find('a')['href'].strip()
|
|
|
449 |
if not trackingUrl.startswith("http"):
|
| 14608 |
amit.gupta |
450 |
trackingUrl = "http://www.amazon.in" + trackingUrl
|
| 13995 |
amit.gupta |
451 |
break
|
|
|
452 |
for prodDiv in productDivs:
|
|
|
453 |
prodDiv.find('div', {'class':'a-fixed-left-grid-inner'})
|
|
|
454 |
productTitle = prodDiv.find('div', {'class':'a-fixed-left-grid-inner'}).find("div", {'class':'a-row'}).find('a').text.strip()
|
|
|
455 |
imgUrl = prodDiv.find("img")["src"]
|
|
|
456 |
for subOrder in activeOrder['subOrders']:
|
|
|
457 |
if subOrder['productTitle'] == productTitle:
|
|
|
458 |
findMap = {"orderId": activeOrder['orderId'], "subOrders.merchantSubOrderId": subOrder.get("merchantSubOrderId")}
|
|
|
459 |
updateMap = {}
|
|
|
460 |
closedStatus = False
|
|
|
461 |
updateMap['subOrders.$.imgUrl'] = imgUrl
|
| 14033 |
amit.gupta |
462 |
updateMap['subOrders.$.lastTracked'] = timestamp
|
| 13995 |
amit.gupta |
463 |
updateMap['subOrders.$.detailedStatus'] = orderStatus
|
|
|
464 |
cashbackStatus = subOrder.get("cashBackStatus")
|
|
|
465 |
updateMap['subOrders.$.status'] = status
|
|
|
466 |
|
|
|
467 |
if status==MStore.ORDER_DELIVERED:
|
| 14291 |
amit.gupta |
468 |
updateMap['subOrders.$.deliveredOn'] = deliveredOn
|
| 13995 |
amit.gupta |
469 |
closedStatus = True
|
|
|
470 |
updateMap['subOrders.$.closed'] = True
|
|
|
471 |
if cashbackStatus == Store.CB_PENDING:
|
| 14607 |
amit.gupta |
472 |
updateMap['subOrders.$.cashBackStatus'] = Store.CB_APPROVED
|
| 13995 |
amit.gupta |
473 |
if status==MStore.ORDER_CANCELLED:
|
|
|
474 |
closedStatus = True
|
|
|
475 |
updateMap['subOrders.$.closed'] = True
|
|
|
476 |
if cashbackStatus == Store.CB_PENDING:
|
|
|
477 |
updateMap['subOrders.$.cashBackStatus'] = Store.CB_CANCELLED
|
|
|
478 |
if status==MStore.ORDER_SHIPPED:
|
|
|
479 |
updateMap['subOrders.$.estimatedDeliveryDate'] = deliveryEstimate
|
|
|
480 |
if trackingUrl is not None:
|
|
|
481 |
updateMap['subOrders.$.trackingUrl'] = trackingUrl
|
|
|
482 |
if not closedStatus:
|
|
|
483 |
closed = False
|
|
|
484 |
bulk.find(findMap).update({'$set' : updateMap})
|
|
|
485 |
break
|
|
|
486 |
bulk.find({'orderId': activeOrder['orderId']}).update({'$set':{'closed': closed}})
|
| 14080 |
amit.gupta |
487 |
bulk.execute()
|
|
|
488 |
return 'PARSED_SUCCESS'
|
|
|
489 |
else:
|
| 14086 |
amit.gupta |
490 |
merchantOrderId = re.findall(r'https://www.amazon.in/gp/css/summary/edit.html\?orderID=(.*)?', url, re.IGNORECASE)[0]
|
| 14085 |
amit.gupta |
491 |
merchantOrder = self.db.merchantOrder.find_one({"merchantOrderId":merchantOrderId})
|
| 14945 |
amit.gupta |
492 |
|
|
|
493 |
filename = directory + "/" + merchantOrderId
|
|
|
494 |
f = open(filename,'w')
|
|
|
495 |
f.write(rawHtml) # python will convert \n to os.linesep
|
|
|
496 |
f.close() # you can omit in most cases as the destructor will call if
|
|
|
497 |
self.parseOrderRawHtml(merchantOrder['orderId'], merchantOrder['subTagId'], merchantOrder['userId'], rawHtml, url, True)['result']
|
| 14080 |
amit.gupta |
498 |
return 'PARSED_SUCCESS'
|
|
|
499 |
pass
|
| 14008 |
amit.gupta |
500 |
return 'PARSED_SUCCESS_NO_ORDERS'
|
| 13995 |
amit.gupta |
501 |
except:
|
|
|
502 |
traceback.print_exc()
|
|
|
503 |
return 'PARSED_FAILED'
|
|
|
504 |
|
|
|
505 |
def _getStatusFromDetailedStatus(self, detailedStatus):
|
| 14061 |
amit.gupta |
506 |
if "ordered from" in detailedStatus.lower():
|
|
|
507 |
return MStore.ORDER_PLACED
|
|
|
508 |
|
| 13995 |
amit.gupta |
509 |
for key, value in self.orderStatusRegexMap.iteritems():
|
| 14032 |
amit.gupta |
510 |
if detailedStatus.lower() in value:
|
| 13995 |
amit.gupta |
511 |
return key
|
|
|
512 |
|
| 14676 |
amit.gupta |
513 |
print "Detailed Status need to be mapped", "Store:", self.store_id
|
| 13995 |
amit.gupta |
514 |
raise ParseException("_getStatusFromDetailedStatus", "Found new order status" + detailedStatus)
|
| 14624 |
amit.gupta |
515 |
def scrapeAffiliate(self, startDate=None, endDate=None):
|
| 14650 |
amit.gupta |
516 |
br = getBrowserObject()
|
|
|
517 |
br.add_password('https://assoc-datafeeds-eu.amazon.com', 'Saholic', 'Fnubyvp')
|
|
|
518 |
url = AMAZON_AFF_URL
|
|
|
519 |
response = br.open(url)
|
|
|
520 |
#get data for past 40 days and store it to mongo
|
|
|
521 |
dt = datetime.now()
|
| 14701 |
amit.gupta |
522 |
dat = dt - timedelta(days=2)
|
| 14651 |
amit.gupta |
523 |
url = AMAZON_AFF_FILE_URL%(datetime.strftime(dat, "%Y%m%d"))
|
|
|
524 |
response = br.open(url)
|
|
|
525 |
page = gzip.GzipFile(fileobj=response, mode='rb').read()
|
|
|
526 |
j=-1
|
|
|
527 |
for row in page.split("\n"):
|
|
|
528 |
j += 1
|
|
|
529 |
if j== 0 or j==1:
|
|
|
530 |
continue
|
|
|
531 |
fields = row.split("\t")
|
|
|
532 |
if len(fields)>1:
|
|
|
533 |
print fields
|
|
|
534 |
amazonAffiliate = AmazonAffiliateInfo(fields[0], fields[1], fields[2], fields[3], fields[4], fields[5], fields[6], fields[7], fields[8], fields[9])
|
|
|
535 |
print amazonAffiliate
|
|
|
536 |
self.db.amazonAffiliateInfo.insert(todict(amazonAffiliate))
|
|
|
537 |
else:
|
|
|
538 |
break
|
| 14650 |
amit.gupta |
539 |
|
| 14608 |
amit.gupta |
540 |
|
| 14749 |
amit.gupta |
541 |
def parseTrackingUrl(self, trackingUrl):
|
| 14624 |
amit.gupta |
542 |
subOrder = {}
|
| 14749 |
amit.gupta |
543 |
page = fetchResponseUsingProxy(trackingUrl)
|
| 14624 |
amit.gupta |
544 |
soup = BeautifulSoup(page)
|
|
|
545 |
alertContainer = soup.find("div", {"class":"a-box-inner a-alert-container"})
|
|
|
546 |
if alertContainer is not None:
|
|
|
547 |
statusText = alertContainer.h4.span.text
|
|
|
548 |
detailedStatus = statusText.split(":")[0].strip()
|
|
|
549 |
subOrder['detailedStatus'] = detailedStatus
|
|
|
550 |
if detailedStatus.lower() == "in transit":
|
|
|
551 |
pass
|
|
|
552 |
elif detailedStatus.lower() == "undeliverable":
|
|
|
553 |
subOrder['status'] = MStore.ORDER_CANCELLED
|
|
|
554 |
return subOrder
|
|
|
555 |
else:
|
|
|
556 |
summaryLeft = soup.find(id="summaryLeft")
|
|
|
557 |
statusText = summaryLeft.h2.text
|
|
|
558 |
detailedStatus = statusText.split(":")[0].strip()
|
|
|
559 |
subOrder['detailedStatus'] = detailedStatus
|
|
|
560 |
if detailedStatus.lower() == "delivered":
|
|
|
561 |
subOrder['deliveredOn'] = summaryLeft.findAll("span")[-2].text.strip()
|
|
|
562 |
subOrder['status'] = MStore.ORDER_DELIVERED
|
|
|
563 |
return subOrder
|
|
|
564 |
else:
|
|
|
565 |
subOrder['expectedDelivery'] = summaryLeft.findAll("span")[-1].text.strip()
|
|
|
566 |
return subOrder
|
|
|
567 |
|
|
|
568 |
|
|
|
569 |
|
| 14608 |
amit.gupta |
570 |
|
|
|
571 |
|
| 13927 |
amit.gupta |
572 |
|
|
|
573 |
|
| 13774 |
amit.gupta |
574 |
def main():
|
| 15346 |
amit.gupta |
575 |
#str1 = readSSh("/AmazonTrack/User533/403-3748792-1516356")
|
| 15046 |
amit.gupta |
576 |
#readSSh("/tmp/User2/404-2225153-7073122")
|
| 14962 |
amit.gupta |
577 |
|
| 15056 |
amit.gupta |
578 |
store = getStore(1)
|
| 14756 |
amit.gupta |
579 |
#store.scrapeStoreOrders()
|
| 14650 |
amit.gupta |
580 |
# br = mechanize.Browser()
|
|
|
581 |
# br.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'),
|
|
|
582 |
# ('Accept', 'text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8'),
|
|
|
583 |
# ('Accept-Encoding', 'gzip,deflate,sdch'),
|
|
|
584 |
# ('Accept-Language', 'en-US,en;q=0.8'),
|
|
|
585 |
# ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3')]
|
|
|
586 |
# store.scrapeStoreOrders()
|
| 15346 |
amit.gupta |
587 |
store.parseOrderRawHtml(1306, "13232", 14, readSSh("/AmazonTrack/User533/403-3748792-1516356"), "https://www.amazon.in/gp/css/summary/edit.html?orderID=403-3748792-1516356")
|
|
|
588 |
#store.trackOrdersForUser(94, "https://www.amazon.in/gp/css/summary/edit.html?orderID=404-5725877-2507524", str1)
|
| 14813 |
amit.gupta |
589 |
#readSSh("/tmp/User211/2015-04-12 10:32:41.905765")
|
| 14703 |
amit.gupta |
590 |
#store.scrapeAffiliate()
|
| 14162 |
amit.gupta |
591 |
def readSSh(fileName):
|
|
|
592 |
try:
|
| 15046 |
amit.gupta |
593 |
str1 = open(fileName).read()
|
|
|
594 |
return str1
|
| 14162 |
amit.gupta |
595 |
except:
|
|
|
596 |
ssh_client = SSHClient()
|
|
|
597 |
str1 = ""
|
|
|
598 |
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
| 15056 |
amit.gupta |
599 |
ssh_client.connect('dtr', 22, 'root', 'ecip$dtrMay2014')
|
| 14162 |
amit.gupta |
600 |
sftp_client = ssh_client.open_sftp()
|
|
|
601 |
try:
|
| 14299 |
amit.gupta |
602 |
if not os.path.exists(os.path.dirname(fileName)):
|
|
|
603 |
os.makedirs(os.path.dirname(fileName))
|
| 14162 |
amit.gupta |
604 |
sftp_client.get(fileName, fileName)
|
|
|
605 |
try:
|
|
|
606 |
str1 = open(fileName).read()
|
|
|
607 |
return str1
|
|
|
608 |
finally:
|
|
|
609 |
pass
|
|
|
610 |
except:
|
|
|
611 |
"could not read"
|
|
|
612 |
return str1
|
| 13774 |
amit.gupta |
613 |
|
|
|
614 |
|
|
|
615 |
if __name__ == '__main__':
|
| 14284 |
amit.gupta |
616 |
main()
|