| 15509 |
manish.sha |
1 |
'''
|
|
|
2 |
Created on Jan 15, 2015
|
|
|
3 |
|
|
|
4 |
@author: Manish
|
|
|
5 |
'''
|
|
|
6 |
from bs4 import BeautifulSoup
|
|
|
7 |
from bson.binary import Binary
|
|
|
8 |
from datetime import datetime, date, timedelta
|
|
|
9 |
from dtr import main
|
| 15791 |
manish.sha |
10 |
from dtr.dao import AffiliateInfo, Order, SubOrder, ShopCluesAffiliateInfo
|
| 15509 |
manish.sha |
11 |
from dtr.main import getBrowserObject, ScrapeException, getStore, ParseException, \
|
|
|
12 |
Store as MStore, ungzipResponse, tprint
|
|
|
13 |
from dtr.storage import Mongo
|
|
|
14 |
from dtr.storage.Mongo import getImgSrc
|
|
|
15 |
from dtr.utils.utils import fetchResponseUsingProxy
|
|
|
16 |
from pprint import pprint
|
|
|
17 |
from pymongo import MongoClient
|
|
|
18 |
import json
|
|
|
19 |
import pymongo
|
|
|
20 |
import re
|
|
|
21 |
import time
|
|
|
22 |
import traceback
|
|
|
23 |
import urllib
|
| 15791 |
manish.sha |
24 |
import urllib2
|
| 15509 |
manish.sha |
25 |
from urlparse import urlparse, parse_qs
|
| 15791 |
manish.sha |
26 |
import xml.etree.ElementTree as ET
|
|
|
27 |
from dtr.storage import MemCache
|
| 15509 |
manish.sha |
28 |
|
|
|
29 |
USERNAME='profittill2@gmail.com'
|
|
|
30 |
PASSWORD='spice@2020'
|
| 15791 |
manish.sha |
31 |
AFFLIATE_TRASACTIONS_URL = "https://admin.optimisemedia.com/v2/reports/affiliate/leads/leadsummaryexport.aspx?Contact=796881&Country=26&Agency=95&Merchant=420562&Status=-1&Year=%d&Month=%d&Day=%d&EndYear=%d&EndMonth=%d&EndDay=%d&DateType=0&Sort=CompletionDate&Login=1347562DA5E3EFF6FB1561765C47C782&Format=XML&RestrictURL=0"
|
| 15509 |
manish.sha |
32 |
ORDER_TRACK_URL='http://www.shopclues.com/index.php?dispatch=order_lookup.details'
|
| 15791 |
manish.sha |
33 |
ORDER_TRACK_URL_DB='https://sm.shopclues.com/trackOrder?'
|
| 15509 |
manish.sha |
34 |
BASE_URL= 'http://www.shopclues.com'
|
|
|
35 |
BASE_MURL= 'http://m.shopclues.com'
|
|
|
36 |
|
|
|
37 |
class Store(MStore):
|
|
|
38 |
|
|
|
39 |
'''
|
|
|
40 |
This is to map order statuses of our system to order statuses of snapdeal.
|
|
|
41 |
And our statuses will change accordingly.
|
|
|
42 |
|
|
|
43 |
'''
|
|
|
44 |
OrderStatusMap = {
|
|
|
45 |
MStore.ORDER_PLACED : ['payment successful', 'new order - cod confirmation pending', 'processing', 'quality check','on schedule', 'processing - pickup-initiated', 'processing - ready to dispatch'],
|
|
|
46 |
MStore.ORDER_DELIVERED : ['delivered', 'complete'],
|
|
|
47 |
MStore.ORDER_SHIPPED : ['in transit', 'dispatched','shipped','order handed to courier'],
|
|
|
48 |
MStore.ORDER_CANCELLED : ['payment failed', 'canceled', 'payment declined', 'order on hold - cancellation requested by customer', 'courier returned']
|
|
|
49 |
}
|
|
|
50 |
OrderStatusConfirmationMap= {
|
| 15791 |
manish.sha |
51 |
"P" : "Payment Successful",
|
|
|
52 |
"D" : "Order Declined",
|
|
|
53 |
"O" : "New Order - COD confirmation Pending"
|
| 15509 |
manish.sha |
54 |
}
|
|
|
55 |
|
|
|
56 |
CONF_CB_AMOUNT = MStore.CONF_CB_DISCOUNTED_PRICE
|
|
|
57 |
|
| 15791 |
manish.sha |
58 |
def convertToObj(self,offer):
|
|
|
59 |
orderRef = offer['TransactionId']
|
|
|
60 |
orderRef = orderRef[0:len(orderRef)-10]
|
|
|
61 |
offer1 = ShopCluesAffiliateInfo(offer['UID'], offer['TransactionTime'], offer['TransactionId'], orderRef, offer['MerchantRef'], offer['Merchant'], offer['PID'], offer['Product'], float(str(offer['SR'])), float(str(offer['TransactionValue'])), offer['UKey'], offer['ClickTime'], offer['Status'])
|
|
|
62 |
return offer1
|
|
|
63 |
|
|
|
64 |
def _saveToAffiliate(self, offers):
|
|
|
65 |
collection = self.db.shopcluesOrderAffiliateInfo
|
|
|
66 |
mcollection = self.db.merchantOrder
|
|
|
67 |
for offerObj in offers:
|
|
|
68 |
offer = self.convertToObj(offerObj)
|
|
|
69 |
collection.update({"transactionId":offer.transactionId, "subTagId":offer.subTagId, "payOut":offer.payOut},{"$set":todict(offer)}, upsert=True)
|
|
|
70 |
mcollection.update({"subTagId":offer.subTagId, "storeId":self.store_id, "subOrders.missingAff":True}, {"$set":{"subOrders.$.missingAff":False}})
|
|
|
71 |
|
| 15940 |
manish.sha |
72 |
def scrapeAffiliate(self, startDate=datetime.today() - timedelta(days=10), endDate=datetime.today()):
|
| 15791 |
manish.sha |
73 |
uri = AFFLIATE_TRASACTIONS_URL%(startDate.year,startDate.month,startDate.day,endDate.year,endDate.month,endDate.day)
|
|
|
74 |
root = ET.parse(urllib2.urlopen(uri)).getroot()
|
|
|
75 |
if len(root)> 0 and len(root[0])> 0:
|
|
|
76 |
offers = []
|
|
|
77 |
for child in root[0][0]:
|
|
|
78 |
offers.append(child.attrib)
|
|
|
79 |
self._saveToAffiliate(offers)
|
|
|
80 |
|
| 15509 |
manish.sha |
81 |
def _setLastSaleDate(self, saleDate):
|
|
|
82 |
self.db.lastSaleDtate.update({'storeId':self.store_id}, {'$set':{'saleDate':saleDate}})
|
|
|
83 |
|
|
|
84 |
def getName(self):
|
|
|
85 |
return "shopclues"
|
|
|
86 |
|
|
|
87 |
def _getLastSaleDate(self,):
|
|
|
88 |
lastDaySaleObj = self.db.lastDaySale.find_one({"storeId":self.store_id})
|
|
|
89 |
if lastDaySaleObj is None:
|
|
|
90 |
return datetime.min
|
|
|
91 |
|
|
|
92 |
def _getStatusFromDetailedStatus(self, detailedStatus):
|
|
|
93 |
for key, value in Store.OrderStatusMap.iteritems():
|
|
|
94 |
if detailedStatus.lower() in value:
|
|
|
95 |
return key
|
|
|
96 |
print "Detailed Status need to be mapped", detailedStatus, self.store_id
|
|
|
97 |
return None
|
|
|
98 |
|
| 15791 |
manish.sha |
99 |
def _getSingleSubOrderMap(self, orderId, soup, orderObj):
|
|
|
100 |
orderStatus = self.OrderStatusConfirmationMap.get(orderObj['0']['status'])
|
|
|
101 |
statusTime= soup.findAll(attrs={'class' : 'sts no_mobile'})[1].contents[2].strip()
|
| 15509 |
manish.sha |
102 |
productDetailsMap = {}
|
|
|
103 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| 15791 |
manish.sha |
104 |
firstRow = orderTable.pop(0)
|
|
|
105 |
totalColumns = len(firstRow.find_all('td'))
|
|
|
106 |
jsonSubOrdersMap = {}
|
|
|
107 |
count = 1
|
|
|
108 |
|
|
|
109 |
for val in orderObj['0']['items'].values():
|
|
|
110 |
newCount = 0
|
|
|
111 |
for key in jsonSubOrdersMap.keys():
|
|
|
112 |
splitKey = key.split('-')
|
|
|
113 |
if str(val['order_id']) == splitKey[0]:
|
|
|
114 |
newCount = int(splitKey[1])
|
|
|
115 |
break
|
|
|
116 |
if newCount >0 :
|
|
|
117 |
count = newCount +1
|
|
|
118 |
jsonSubOrdersMap[str(val['order_id'])+'-'+str(count)] = val
|
|
|
119 |
else:
|
|
|
120 |
jsonSubOrdersMap[str(val['order_id'])+'-'+str(count)] = val
|
|
|
121 |
|
|
|
122 |
count= count+1
|
|
|
123 |
|
|
|
124 |
count = 1
|
| 15509 |
manish.sha |
125 |
for orderTr in orderTable:
|
| 15791 |
manish.sha |
126 |
productDetailsSubMap = None
|
|
|
127 |
productDetailsSubMap = {}
|
| 15509 |
manish.sha |
128 |
cols = orderTr.find_all('td')
|
|
|
129 |
product_details = cols[0].find_all('a')
|
|
|
130 |
#print product_details
|
|
|
131 |
productUrl = product_details[0].get('href')
|
|
|
132 |
productName = product_details[0].contents[0].strip()
|
|
|
133 |
quantity = int(cols[1].text.strip())
|
|
|
134 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
| 15791 |
manish.sha |
135 |
discount = 0
|
|
|
136 |
subtotal = 0
|
|
|
137 |
if totalColumns == 5:
|
|
|
138 |
if cols[3].text.strip()!='-' or 'Rs.' in cols[3].text.strip():
|
|
|
139 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
|
|
140 |
else:
|
|
|
141 |
discount = 0
|
|
|
142 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
|
|
143 |
else:
|
|
|
144 |
subtotal = long(cols[3].text.strip().replace("Rs.",""))
|
| 15509 |
manish.sha |
145 |
productDetailsSubMap['productUrl']=BASE_MURL+productUrl
|
|
|
146 |
productDetailsSubMap['productName']=productName
|
| 15791 |
manish.sha |
147 |
productDetailsSubMap['subOrderTrackingUrl']=ORDER_TRACK_URL_DB+'order_id=' +str(orderId)+'&email_id='+ orderObj['0']['email']
|
| 15509 |
manish.sha |
148 |
productDetailsSubMap['sellingPrice']=sellingPrice
|
|
|
149 |
productDetailsSubMap['quantity']=quantity
|
|
|
150 |
productDetailsSubMap['discount']=discount
|
|
|
151 |
productDetailsSubMap['subtotal']=subtotal
|
| 15791 |
manish.sha |
152 |
jsonSubOrderDetails = jsonSubOrdersMap.get(str(orderId)+'-'+str(count))
|
|
|
153 |
productCode = jsonSubOrderDetails['product_code']
|
|
|
154 |
productImgUrl = jsonSubOrderDetails['images']['image_path'][0]
|
| 15509 |
manish.sha |
155 |
productDetailsSubMap['productCode']=productCode
|
|
|
156 |
productDetailsSubMap['imgUrl']=productImgUrl
|
|
|
157 |
|
| 15791 |
manish.sha |
158 |
productDetailsSubMap['subOrderStatus']=orderStatus
|
|
|
159 |
productDetailsSubMap['subOrderStatusTime']=statusTime
|
|
|
160 |
productDetailsMap[str(orderId)+'-'+str(count)]=productDetailsSubMap
|
|
|
161 |
count = count +1
|
| 15509 |
manish.sha |
162 |
return productDetailsMap
|
|
|
163 |
|
| 15791 |
manish.sha |
164 |
def _getMultiSubOrdersMap(self, orderId, soup, orderObj):
|
| 15509 |
manish.sha |
165 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| 15791 |
manish.sha |
166 |
#firstRow = orderTable.pop(0)
|
|
|
167 |
#totalColumns = len(firstRow.find_all('td'))
|
| 15509 |
manish.sha |
168 |
productDetailsMap = {}
|
| 15791 |
manish.sha |
169 |
'''
|
|
|
170 |
jsonSubOrdersMap = {}
|
|
|
171 |
for val in orderObj['0']['items'].values():
|
|
|
172 |
jsonSubOrdersMap[val['order_id']] = val
|
|
|
173 |
'''
|
|
|
174 |
existingOrders = []
|
| 15509 |
manish.sha |
175 |
for orderTr in orderTable:
|
| 15791 |
manish.sha |
176 |
subOrderDetailsMap = {}
|
|
|
177 |
|
| 15509 |
manish.sha |
178 |
cols = orderTr.find_all('td')
|
|
|
179 |
product_details = cols[0].find_all('a')
|
|
|
180 |
#print product_details
|
|
|
181 |
subOrderId= product_details[1].contents[0].strip()
|
| 15791 |
manish.sha |
182 |
if subOrderId in existingOrders:
|
|
|
183 |
continue
|
|
|
184 |
else:
|
|
|
185 |
existingOrders.append(subOrderId)
|
|
|
186 |
#productUrl = product_details[0].get('href')
|
|
|
187 |
#productName = product_details[0].contents[0].strip()
|
|
|
188 |
subOrderTrackingParsingUrl = product_details[1].get('href')
|
|
|
189 |
#subOrderTrackingUrl = subOrderTrackingParsingUrl.split('order_lookup.details&')[1]
|
|
|
190 |
'''
|
| 15509 |
manish.sha |
191 |
quantity = int(cols[1].text.strip())
|
|
|
192 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
| 15791 |
manish.sha |
193 |
discount = 0
|
|
|
194 |
subtotal = 0
|
|
|
195 |
if totalColumns == 5:
|
|
|
196 |
if cols[3].text.strip()!='-' or 'Rs.' in cols[3].text.strip():
|
|
|
197 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
|
|
198 |
else:
|
|
|
199 |
discount = 0
|
|
|
200 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
|
|
201 |
else:
|
|
|
202 |
subtotal = long(cols[3].text.strip().replace("Rs.",""))
|
| 15509 |
manish.sha |
203 |
productDetailsSubMap['productUrl']=BASE_MURL+productUrl
|
|
|
204 |
productDetailsSubMap['productName']=productName
|
| 15791 |
manish.sha |
205 |
productDetailsSubMap['subOrderTrackingUrl']=ORDER_TRACK_URL_DB+subOrderTrackingUrl
|
| 15509 |
manish.sha |
206 |
productDetailsSubMap['sellingPrice']=sellingPrice
|
|
|
207 |
productDetailsSubMap['quantity']=quantity
|
|
|
208 |
productDetailsSubMap['discount']=discount
|
|
|
209 |
productDetailsSubMap['subtotal']=subtotal
|
| 15791 |
manish.sha |
210 |
jsonSubOrderDetails = jsonSubOrdersMap.get(subOrderId)
|
|
|
211 |
productCode = jsonSubOrderDetails['product_code']
|
|
|
212 |
productImgUrl = jsonSubOrderDetails['images']['image_path'][0]
|
| 15509 |
manish.sha |
213 |
productDetailsSubMap['productCode']=productCode
|
|
|
214 |
productDetailsSubMap['imgUrl']=productImgUrl
|
| 15791 |
manish.sha |
215 |
'''
|
| 15509 |
manish.sha |
216 |
br1 = getBrowserObject()
|
| 15791 |
manish.sha |
217 |
orderTrackingPage = br1.open(BASE_URL+'&'+subOrderTrackingParsingUrl)
|
| 15509 |
manish.sha |
218 |
headers = str(orderTrackingPage.info()).split('\n')
|
|
|
219 |
orderTrackingPage= ungzipResponse(orderTrackingPage)
|
|
|
220 |
jsonResponse = None
|
|
|
221 |
for header in headers:
|
|
|
222 |
header = header.split(':')
|
|
|
223 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
|
|
224 |
jsonResponse = json.loads(orderTrackingPage)
|
|
|
225 |
|
|
|
226 |
orderTrackingPageSoup = None
|
|
|
227 |
if jsonResponse is not None:
|
|
|
228 |
orderTrackingPageSoup = BeautifulSoup(str(jsonResponse['text']))
|
|
|
229 |
else:
|
|
|
230 |
orderTrackingPageSoup = BeautifulSoup(orderTrackingPage)
|
| 15791 |
manish.sha |
231 |
'''
|
| 15509 |
manish.sha |
232 |
subOrderStatusList = orderTrackingPageSoup.findAll(attrs={'class' : 'price ord_status'})
|
|
|
233 |
subOrderStatus = subOrderStatusList[0].contents[0].strip()
|
|
|
234 |
subOrderStatusTime= orderTrackingPageSoup.findAll(attrs={'class' : 'sts no_mobile'})[1].contents[2].strip()
|
|
|
235 |
productDetailsSubMap['subOrderStatus'] = subOrderStatus
|
|
|
236 |
productDetailsSubMap['subOrderStatusTime'] = subOrderStatusTime
|
|
|
237 |
productDetailsSubMap['parentOrderId']=orderId
|
| 15791 |
manish.sha |
238 |
'''
|
|
|
239 |
|
|
|
240 |
subOrderDetailsMap = self._getSingleSubOrderMap(subOrderId, orderTrackingPageSoup, orderObj)
|
| 15509 |
manish.sha |
241 |
|
| 15791 |
manish.sha |
242 |
productDetailsMap = dict(productDetailsMap.items()+subOrderDetailsMap.items())
|
| 15509 |
manish.sha |
243 |
|
|
|
244 |
return productDetailsMap
|
|
|
245 |
|
|
|
246 |
def updateCashbackInSubOrders(self, subOrders):
|
|
|
247 |
for subOrder in subOrders:
|
|
|
248 |
cashbackStatus = Store.CB_NA
|
|
|
249 |
cashbackAmount = 0
|
|
|
250 |
percentage = 0
|
|
|
251 |
amount = subOrder.amountPaid
|
|
|
252 |
if amount > 0:
|
|
|
253 |
(cashbackAmount, percentage) = self.getCashbackAmount(subOrder.productCode, amount)
|
|
|
254 |
if cashbackAmount > 0:
|
|
|
255 |
cashbackStatus = Store.CB_PENDING
|
|
|
256 |
subOrder.cashBackStatus = cashbackStatus
|
|
|
257 |
subOrder.cashBackAmount = cashbackAmount
|
|
|
258 |
subOrder.cashBackPercentage = percentage
|
|
|
259 |
return subOrders
|
|
|
260 |
|
| 15791 |
manish.sha |
261 |
def _parseOrders(self, orderId, subTagId, userId, page, orderSuccessUrl, orderObj):
|
| 15509 |
manish.sha |
262 |
soup = BeautifulSoup(page)
|
|
|
263 |
productDetailsMap = {}
|
|
|
264 |
paymentFields = soup.findAll(attrs={'class' : 'box_paymentcalculations_row'})
|
|
|
265 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
|
|
266 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace(" ","")
|
|
|
267 |
ordersubtotal=0
|
|
|
268 |
ordercluebucks=0
|
|
|
269 |
ordershippingcost=0
|
|
|
270 |
ordertotal=0
|
|
|
271 |
|
|
|
272 |
for val in paymentFields:
|
|
|
273 |
for value in val.contents:
|
|
|
274 |
if value is not None:
|
|
|
275 |
if 'div' in str(value).strip():
|
|
|
276 |
if 'Subtotal' in value.text.strip():
|
|
|
277 |
ordersubtotal = long(val.contents[3].text.strip().replace("Rs.",""))
|
|
|
278 |
print ordersubtotal
|
|
|
279 |
if 'Shipping Cost' in value.text.strip():
|
|
|
280 |
ordershippingcost = long(val.contents[3].text.strip().replace("Rs.",""))
|
|
|
281 |
print ordershippingcost
|
|
|
282 |
if 'Clue' in value.text.strip():
|
|
|
283 |
ordercluebucks = long(val.contents[3].text.strip().replace("Rs.",""))
|
|
|
284 |
print ordercluebucks
|
|
|
285 |
if 'Total' in value.text.strip():
|
| 15791 |
manish.sha |
286 |
ordertotal = val.contents[3].text.strip().replace("Rs.","")
|
|
|
287 |
ordertotal = ordertotal.replace(',','')
|
| 15509 |
manish.sha |
288 |
print ordertotal
|
| 15791 |
manish.sha |
289 |
|
|
|
290 |
if orderObj['0']['is_parent_order'] == 'N':
|
|
|
291 |
productDetailsMap = self._getSingleSubOrderMap(orderId, soup, orderObj)
|
| 15509 |
manish.sha |
292 |
else:
|
| 15791 |
manish.sha |
293 |
productDetailsMap = self._getMultiSubOrdersMap(orderId, soup, orderObj)
|
| 15509 |
manish.sha |
294 |
|
| 15791 |
manish.sha |
295 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
|
| 15509 |
manish.sha |
296 |
merchantOrder.placedOn = placedOn
|
| 15791 |
manish.sha |
297 |
merchantOrder.merchantOrderId = orderObj['0']['order_id']
|
| 15509 |
manish.sha |
298 |
merchantOrder.paidAmount = ordertotal
|
|
|
299 |
totalOrdersAmount = 0
|
|
|
300 |
totalDiscount = 0
|
|
|
301 |
subOrders= []
|
|
|
302 |
for key in productDetailsMap:
|
|
|
303 |
subOrderDetail = productDetailsMap.get(key)
|
|
|
304 |
totalOrdersAmount = totalOrdersAmount + (subOrderDetail['sellingPrice'] * subOrderDetail['quantity'])
|
|
|
305 |
totalDiscount = totalDiscount + (subOrderDetail['discount'] * subOrderDetail['quantity'])
|
|
|
306 |
subOrder = SubOrder(subOrderDetail['productName'], subOrderDetail['productUrl'], placedOn, subOrderDetail['subtotal'])
|
|
|
307 |
subOrder.merchantSubOrderId = key
|
|
|
308 |
subOrder.detailedStatus = subOrderDetail['subOrderStatus']
|
|
|
309 |
subOrder.imgUrl = subOrderDetail['imgUrl']
|
|
|
310 |
subOrder.offerDiscount = subOrderDetail['discount'] * subOrderDetail['quantity']
|
|
|
311 |
subOrder.unitPrice = subOrderDetail['sellingPrice']
|
|
|
312 |
subOrder.productCode = subOrderDetail['productCode']
|
|
|
313 |
subOrder.amountPaid = subOrderDetail['subtotal']
|
|
|
314 |
subOrder.quantity = subOrderDetail['quantity']
|
| 15791 |
manish.sha |
315 |
subOrder.tracingkUrl = subOrderDetail['subOrderTrackingUrl']
|
| 15509 |
manish.sha |
316 |
subOrders.append(subOrder)
|
|
|
317 |
print totalOrdersAmount, totalDiscount
|
|
|
318 |
merchantOrder.totalAmount = totalOrdersAmount
|
|
|
319 |
merchantOrder.discountApplied = totalDiscount
|
|
|
320 |
merchantOrder.deliveryCharges = ordershippingcost
|
|
|
321 |
merchantOrder.subOrders = self.updateCashbackInSubOrders(subOrders)
|
|
|
322 |
|
|
|
323 |
return merchantOrder
|
|
|
324 |
|
|
|
325 |
def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
|
|
|
326 |
resp = {}
|
|
|
327 |
try:
|
| 15791 |
manish.sha |
328 |
rawHtmlSoup = BeautifulSoup(rawHtml)
|
|
|
329 |
emailId = None
|
|
|
330 |
orderObj = None
|
|
|
331 |
merchantOrderId = None
|
|
|
332 |
for script in rawHtmlSoup.find_all('script'):
|
|
|
333 |
if 'orderConfirmation' in script.text:
|
|
|
334 |
orderObj = json.loads(script.text.strip().split('\n')[0].split('orderConfirmation = ')[1].split(';')[0])
|
|
|
335 |
if merchantOrderId is None:
|
|
|
336 |
merchantOrderId = orderObj['0']['order_id']
|
|
|
337 |
emailId = orderObj['0']['email']
|
|
|
338 |
|
| 15509 |
manish.sha |
339 |
br = getBrowserObject()
|
| 15791 |
manish.sha |
340 |
url = ORDER_TRACK_URL +'&order_id=' +str(merchantOrderId)+'&email_id='+ emailId
|
| 15509 |
manish.sha |
341 |
page = br.open(url)
|
|
|
342 |
headers = str(page.info()).split('\n')
|
|
|
343 |
page = ungzipResponse(page)
|
|
|
344 |
jsonResponse = None
|
|
|
345 |
for header in headers:
|
|
|
346 |
header = header.split(':')
|
|
|
347 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
|
|
348 |
jsonResponse = json.loads(page)
|
|
|
349 |
if jsonResponse is not None:
|
|
|
350 |
page = jsonResponse['text']
|
|
|
351 |
|
| 15791 |
manish.sha |
352 |
merchantOrder = self._parseOrders(orderId, subTagId, userId, page, orderSuccessUrl, orderObj)
|
| 15509 |
manish.sha |
353 |
|
| 15791 |
manish.sha |
354 |
merchantOrder.orderTrackingUrl = ORDER_TRACK_URL_DB + 'order_id=' +str(orderId)+'&email_id='+ emailId
|
| 15509 |
manish.sha |
355 |
|
|
|
356 |
if self._saveToOrder(todict(merchantOrder)):
|
|
|
357 |
resp['result'] = 'ORDER_CREATED'
|
|
|
358 |
else:
|
|
|
359 |
resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
|
|
|
360 |
|
|
|
361 |
return resp
|
|
|
362 |
except:
|
|
|
363 |
print "Error occurred"
|
|
|
364 |
traceback.print_exc()
|
|
|
365 |
resp['result'] = 'ORDER_NOT_CREATED'
|
|
|
366 |
|
| 15791 |
manish.sha |
367 |
def parseSingleSubOrder(self, soup, emailId, subOrderId):
|
|
|
368 |
orderStatusList = soup.findAll(attrs={'class' : 'price ord_status'})
|
|
|
369 |
subOrderStatus = orderStatusList[0].contents[0].strip()
|
| 15509 |
manish.sha |
370 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
|
|
371 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace(" ","")
|
|
|
372 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| 15791 |
manish.sha |
373 |
firstRow = orderTable.pop(0)
|
|
|
374 |
totalColumns = len(firstRow.find_all('td'))
|
|
|
375 |
subOrders =[]
|
|
|
376 |
count =1
|
| 15509 |
manish.sha |
377 |
for orderTr in orderTable:
|
|
|
378 |
cols = orderTr.find_all('td')
|
|
|
379 |
product_details = cols[0].find_all('a')
|
|
|
380 |
#print product_details
|
|
|
381 |
productUrl = product_details[0].get('href')
|
|
|
382 |
productName = product_details[0].contents[0].strip()
|
|
|
383 |
quantity = int(cols[1].text.strip())
|
|
|
384 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
| 15791 |
manish.sha |
385 |
discount = 0
|
|
|
386 |
subtotal = 0
|
|
|
387 |
if totalColumns == 5:
|
|
|
388 |
if cols[3].text.strip()!='-' or 'Rs.' in cols[3].text.strip():
|
|
|
389 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
|
|
390 |
else:
|
|
|
391 |
discount = 0
|
|
|
392 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
|
|
393 |
else:
|
|
|
394 |
subtotal = long(cols[3].text.strip().replace("Rs.",""))
|
| 15509 |
manish.sha |
395 |
br = getBrowserObject()
|
|
|
396 |
productPage = br.open(BASE_MURL+productUrl)
|
|
|
397 |
productPageHeaders = str(productPage.info()).split('\n')
|
|
|
398 |
productPage = ungzipResponse(productPage)
|
|
|
399 |
jsonProductResponse = None
|
|
|
400 |
for header in productPageHeaders:
|
|
|
401 |
header = header.split(':')
|
|
|
402 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
|
|
403 |
jsonProductResponse = json.loads(productPage)
|
|
|
404 |
productPageSoup= None
|
|
|
405 |
if jsonProductResponse is not None:
|
|
|
406 |
productPageSoup = BeautifulSoup(jsonProductResponse['text'])
|
|
|
407 |
else:
|
|
|
408 |
productPageSoup = BeautifulSoup(productPage)
|
| 15791 |
manish.sha |
409 |
productCode = productPageSoup.find('input', {'type':'hidden'})['value']
|
| 15509 |
manish.sha |
410 |
allproductImageTags = productPageSoup.findAll(attrs={'class' : 'pd-image'})
|
|
|
411 |
productImgUrl = ''
|
|
|
412 |
if allproductImageTags is not None and len(allproductImageTags)>0:
|
|
|
413 |
productImgUrl= allproductImageTags[0].get('style').split("background:url('")[1].split("')no-repeat center")[0].strip()
|
|
|
414 |
|
|
|
415 |
subOrder = SubOrder(productName, productUrl, placedOn, subtotal)
|
| 15791 |
manish.sha |
416 |
subOrder.merchantSubOrderId = str(subOrderId)+'-'+str(count)
|
| 15509 |
manish.sha |
417 |
subOrder.detailedStatus = subOrderStatus
|
|
|
418 |
subOrder.imgUrl = productImgUrl
|
|
|
419 |
subOrder.offerDiscount = discount*quantity
|
|
|
420 |
subOrder.unitPrice = sellingPrice
|
|
|
421 |
subOrder.productCode = productCode
|
|
|
422 |
subOrder.amountPaid = subtotal
|
|
|
423 |
subOrder.quantity = quantity
|
| 15791 |
manish.sha |
424 |
subOrder.tracingkUrl = ORDER_TRACK_URL_DB + 'order_id=' +subOrderId+'&email_id='+ emailId
|
| 15509 |
manish.sha |
425 |
subOrders.append(subOrder)
|
| 15791 |
manish.sha |
426 |
count = count +1
|
| 15509 |
manish.sha |
427 |
|
|
|
428 |
subOrders = self.updateCashbackInSubOrders(subOrders)
|
| 15791 |
manish.sha |
429 |
return subOrders
|
| 15509 |
manish.sha |
430 |
|
| 15791 |
manish.sha |
431 |
def parseMultiSubOrders(self, soup, emailId):
|
| 15509 |
manish.sha |
432 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| 15791 |
manish.sha |
433 |
'''
|
|
|
434 |
firstRow = orderTable.pop(0)
|
|
|
435 |
totalColumns = len(firstRow.find_all('td'))
|
|
|
436 |
|
| 15509 |
manish.sha |
437 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
| 15791 |
manish.sha |
438 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace(" ","")
|
|
|
439 |
'''
|
| 15509 |
manish.sha |
440 |
subOrders = []
|
| 15791 |
manish.sha |
441 |
existingOrders = []
|
| 15509 |
manish.sha |
442 |
for orderTr in orderTable:
|
|
|
443 |
cols = orderTr.find_all('td')
|
|
|
444 |
product_details = cols[0].find_all('a')
|
|
|
445 |
#print product_details
|
|
|
446 |
subOrderId= product_details[1].contents[0].strip()
|
| 15791 |
manish.sha |
447 |
if subOrderId in existingOrders:
|
|
|
448 |
continue
|
|
|
449 |
else:
|
|
|
450 |
existingOrders.append(subOrderId)
|
|
|
451 |
'''
|
| 15509 |
manish.sha |
452 |
productUrl = product_details[0].get('href')
|
|
|
453 |
productName = product_details[0].contents[0].strip()
|
| 15791 |
manish.sha |
454 |
'''
|
|
|
455 |
subOrderTrackingParsingUrl = product_details[1].get('href')
|
|
|
456 |
#subOrderTrackingUrl = subOrderTrackingParsingUrl.split('order_lookup.details&')[1]
|
|
|
457 |
'''
|
| 15509 |
manish.sha |
458 |
quantity = int(cols[1].text.strip())
|
|
|
459 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
| 15791 |
manish.sha |
460 |
discount = 0
|
|
|
461 |
subtotal = 0
|
|
|
462 |
if totalColumns == 5:
|
|
|
463 |
if cols[3].text.strip()!='-' or 'Rs.' in cols[3].text.strip():
|
|
|
464 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
|
|
465 |
else:
|
|
|
466 |
discount = 0
|
|
|
467 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
|
|
468 |
else:
|
|
|
469 |
subtotal = long(cols[3].text.strip().replace("Rs.",""))
|
|
|
470 |
|
| 15509 |
manish.sha |
471 |
br = getBrowserObject()
|
|
|
472 |
productPage = br.open(BASE_MURL+productUrl)
|
|
|
473 |
productPageHeaders = str(productPage.info()).split('\n')
|
|
|
474 |
productPage = ungzipResponse(productPage)
|
|
|
475 |
jsonProductResponse = None
|
|
|
476 |
for header in productPageHeaders:
|
|
|
477 |
header = header.split(':')
|
|
|
478 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
|
|
479 |
jsonProductResponse = json.loads(productPage)
|
|
|
480 |
productPageSoup= None
|
|
|
481 |
if jsonProductResponse is not None:
|
|
|
482 |
productPageSoup = BeautifulSoup(jsonProductResponse['text'])
|
|
|
483 |
else:
|
|
|
484 |
productPageSoup = BeautifulSoup(productPage)
|
| 15791 |
manish.sha |
485 |
productCode = productPageSoup.find('input', {'type':'hidden'})['value']
|
| 15509 |
manish.sha |
486 |
allproductImageTags = productPageSoup.findAll(attrs={'class' : 'pd-image'})
|
|
|
487 |
productImgUrl = ''
|
|
|
488 |
if allproductImageTags is not None and len(allproductImageTags)>0:
|
|
|
489 |
productImgUrl= allproductImageTags[0].get('style').split("background:url('")[1].split("')no-repeat center")[0].strip()
|
|
|
490 |
productDetailsSubMap['productCode']=productCode
|
|
|
491 |
productDetailsSubMap['imgUrl']=productImgUrl
|
| 15791 |
manish.sha |
492 |
'''
|
| 15509 |
manish.sha |
493 |
br1 = getBrowserObject()
|
| 15791 |
manish.sha |
494 |
orderTrackingPage = br1.open(BASE_URL+'&'+subOrderTrackingParsingUrl)
|
| 15509 |
manish.sha |
495 |
headers = str(orderTrackingPage.info()).split('\n')
|
|
|
496 |
orderTrackingPage= ungzipResponse(orderTrackingPage)
|
|
|
497 |
jsonResponse = None
|
|
|
498 |
for header in headers:
|
|
|
499 |
header = header.split(':')
|
|
|
500 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
|
|
501 |
jsonResponse = json.loads(orderTrackingPage)
|
|
|
502 |
|
|
|
503 |
orderTrackingPageSoup = None
|
|
|
504 |
if jsonResponse is not None:
|
|
|
505 |
orderTrackingPageSoup = BeautifulSoup(str(jsonResponse['text']))
|
|
|
506 |
else:
|
|
|
507 |
orderTrackingPageSoup = BeautifulSoup(orderTrackingPage)
|
| 15791 |
manish.sha |
508 |
subOrdersDetails = self.parseSingleSubOrder(orderTrackingPageSoup, emailId, subOrderId)
|
|
|
509 |
subOrders = list(set(subOrders + subOrdersDetails))
|
| 15509 |
manish.sha |
510 |
|
| 15791 |
manish.sha |
511 |
return subOrders
|
| 15509 |
manish.sha |
512 |
|
|
|
513 |
def scrapeStoreOrders(self,):
|
|
|
514 |
#collectionMap = {'palcedOn':1}
|
|
|
515 |
searchMap = {}
|
|
|
516 |
collectionMap = {"orderTrackingUrl":1}
|
|
|
517 |
orders = self._getActiveOrders(searchMap,collectionMap)
|
|
|
518 |
for order in orders:
|
|
|
519 |
print "Order", self.store_name, order['orderId'], order['orderTrackingUrl']
|
| 15791 |
manish.sha |
520 |
url = ORDER_TRACK_URL + order['orderTrackingUrl'].split('trackOrder?')[1]
|
| 15509 |
manish.sha |
521 |
page = fetchResponseUsingProxy(url)
|
|
|
522 |
soup = BeautifulSoup(page)
|
|
|
523 |
bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
|
|
524 |
closed = True
|
|
|
525 |
orderStatusList = soup.findAll(attrs={'class' : 'price ord_status'})
|
|
|
526 |
if orderStatusList is not None and len(orderStatusList)>0:
|
|
|
527 |
subOrderId = soup.findAll(attrs={'class':'price ord_no'})[0].text.strip()
|
|
|
528 |
orderStatus = orderStatusList[0].contents[0].strip()
|
| 15791 |
manish.sha |
529 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
|
|
530 |
orderTable.pop(0)
|
|
|
531 |
count = 1
|
|
|
532 |
while count <= len(orderTable):
|
|
|
533 |
subOrder = self._isSubOrderActive(order, str(subOrderId)+'-'+str(count))
|
|
|
534 |
count = count +1
|
|
|
535 |
if subOrder is None:
|
|
|
536 |
try:
|
|
|
537 |
subOrders = self.parseSingleSubOrder(soup, order['orderTrackingUrl'].split('email_id=')[1], subOrderId)
|
|
|
538 |
for subOrder in subOrders:
|
|
|
539 |
if subOrder is None:
|
|
|
540 |
continue
|
|
|
541 |
self.db.merchantOrder.update({"orderId":order['orderId']},{'$push':{"subOrders":{"$each":todict([subOrder])}}})
|
|
|
542 |
print "Added new suborders to Order id - ", order['orderId']
|
|
|
543 |
closed = False
|
|
|
544 |
except:
|
|
|
545 |
pass
|
|
|
546 |
continue
|
|
|
547 |
elif subOrder['closed']:
|
|
|
548 |
continue
|
| 15509 |
manish.sha |
549 |
else:
|
| 15791 |
manish.sha |
550 |
findMap = {"orderId": order['orderId'], "subOrders.merchantSubOrderId": subOrderId}
|
|
|
551 |
updateMap = {}
|
|
|
552 |
updateMap["subOrders.$.detailedStatus"] = orderStatus
|
|
|
553 |
status = self._getStatusFromDetailedStatus(orderStatus)
|
|
|
554 |
closedStatus = status in [Store.ORDER_DELIVERED, Store.ORDER_CANCELLED]
|
|
|
555 |
if status is not None:
|
|
|
556 |
updateMap["subOrders.$.status"] = status
|
|
|
557 |
if closedStatus:
|
|
|
558 |
#if status is closed then change the paybackStatus accordingly
|
|
|
559 |
updateMap["subOrders.$.closed"] = True
|
|
|
560 |
if status == Store.ORDER_DELIVERED:
|
|
|
561 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
562 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_APPROVED
|
|
|
563 |
elif status == Store.ORDER_CANCELLED:
|
|
|
564 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
565 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_CANCELLED
|
|
|
566 |
else:
|
|
|
567 |
closed = False
|
|
|
568 |
bulk.find(findMap).update({'$set' : updateMap})
|
| 15509 |
manish.sha |
569 |
|
|
|
570 |
else:
|
| 15791 |
manish.sha |
571 |
subOrdersList = self.parseMultiSubOrders(soup, order['orderTrackingUrl'].split('email_id=')[1])
|
| 15509 |
manish.sha |
572 |
for subOrderObj in subOrdersList:
|
|
|
573 |
subOrder = self._isSubOrderActive(order, subOrderObj.merchantSubOrderId)
|
|
|
574 |
if subOrder is None:
|
|
|
575 |
self.db.merchantOrder.update({"orderId":order['orderId']},{'$push':{"subOrders":{"$each":todict([subOrderObj])}}})
|
|
|
576 |
print "Added new suborders to Order id - ", order['orderId']
|
|
|
577 |
closed = False
|
|
|
578 |
continue
|
|
|
579 |
elif subOrder['closed']:
|
|
|
580 |
continue
|
|
|
581 |
else:
|
|
|
582 |
findMap = {"orderId": order['orderId'], "subOrders.merchantSubOrderId": subOrderId}
|
|
|
583 |
updateMap = {}
|
|
|
584 |
updateMap["subOrders.$.detailedStatus"] = subOrderObj.detailedStatus
|
|
|
585 |
status = self._getStatusFromDetailedStatus(orderStatus)
|
|
|
586 |
closedStatus = status in [Store.ORDER_DELIVERED, Store.ORDER_CANCELLED]
|
|
|
587 |
if status is not None:
|
|
|
588 |
updateMap["subOrders.$.status"] = status
|
|
|
589 |
if closedStatus:
|
|
|
590 |
#if status is closed then change the paybackStatus accordingly
|
|
|
591 |
updateMap["subOrders.$.closed"] = True
|
|
|
592 |
if status == Store.ORDER_DELIVERED:
|
|
|
593 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
594 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_APPROVED
|
|
|
595 |
elif status == Store.ORDER_CANCELLED:
|
|
|
596 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
597 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_CANCELLED
|
|
|
598 |
else:
|
|
|
599 |
closed = False
|
| 15510 |
manish.sha |
600 |
bulk.find(findMap).update({'$set' : updateMap})
|
| 15509 |
manish.sha |
601 |
bulk.find({'orderId': order['orderId']}).update({'$set':{'closed': closed,"parseError":False}})
|
|
|
602 |
result = bulk.execute()
|
|
|
603 |
tprint(result)
|
| 15791 |
manish.sha |
604 |
|
|
|
605 |
'''
|
|
|
606 |
def getTrackingUrls(self, userId):
|
|
|
607 |
missingOrderUrls = ['https://sm.shopclues.com/myaccount','https://sm.shopclues.com/myorders']
|
|
|
608 |
return missingOrderUrls
|
| 15509 |
manish.sha |
609 |
|
| 15791 |
manish.sha |
610 |
def parseMyProfileForEmailId(self, userId, url, rawhtml):
|
|
|
611 |
profileSoup = BeautifulSoup(rawhtml)
|
|
|
612 |
if profileSoup.find('input', {'name':'user_email'}) is not None:
|
|
|
613 |
emailId = profileSoup.find('input', {'name':'user_email'})['value']
|
|
|
614 |
if emailId is not None and emailId.strip() !='':
|
|
|
615 |
mc = MemCache()
|
|
|
616 |
mc.set(str(userId), emailId, 600)
|
|
|
617 |
return 'EMAIL_SET_SUCCESS'
|
|
|
618 |
else:
|
|
|
619 |
return 'EMAIL_NOT_FOUND'
|
|
|
620 |
else:
|
|
|
621 |
return 'EMAIL_NOT_FOUND'
|
| 15509 |
manish.sha |
622 |
|
| 15791 |
manish.sha |
623 |
def parseMyOrdersForEmailId(self, userId, url, rawhtml):
|
|
|
624 |
myOrdersPageSoup = BeautifulSoup(rawhtml)
|
|
|
625 |
if myOrdersPageSoup.find('a', {'class':'detail'}) is not None:
|
|
|
626 |
emailId = myOrdersPageSoup.find('a', {'class':'detail'})['href'].split('&')[1].split('=')[1]
|
|
|
627 |
mc = MemCache()
|
|
|
628 |
mc.set(str(userId), emailId, 600)
|
|
|
629 |
return 'EMAIL_SET_SUCCESS'
|
|
|
630 |
else:
|
|
|
631 |
return 'EMAIL_NOT_FOUND'
|
|
|
632 |
'''
|
|
|
633 |
|
|
|
634 |
|
| 15509 |
manish.sha |
635 |
def todict(obj, classkey=None):
|
|
|
636 |
if isinstance(obj, dict):
|
|
|
637 |
data = {}
|
|
|
638 |
for (k, v) in obj.items():
|
|
|
639 |
data[k] = todict(v, classkey)
|
|
|
640 |
return data
|
|
|
641 |
elif hasattr(obj, "_ast"):
|
|
|
642 |
return todict(obj._ast())
|
|
|
643 |
elif hasattr(obj, "__iter__"):
|
|
|
644 |
return [todict(v, classkey) for v in obj]
|
|
|
645 |
elif hasattr(obj, "__dict__"):
|
|
|
646 |
data = dict([(key, todict(value, classkey))
|
|
|
647 |
for key, value in obj.__dict__.iteritems()
|
|
|
648 |
if not callable(value) and not key.startswith('_')])
|
|
|
649 |
if classkey is not None and hasattr(obj, "__class__"):
|
|
|
650 |
data[classkey] = obj.__class__.__name__
|
|
|
651 |
return data
|
|
|
652 |
else:
|
| 15791 |
manish.sha |
653 |
return obj
|
|
|
654 |
|
| 15509 |
manish.sha |
655 |
|