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