| 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
|
| 16787 |
manish.sha |
15 |
from dtr.utils.utils import fetchResponseUsingProxy, PROXY_MESH_GENERAL
|
| 15509 |
manish.sha |
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 |
|
| 15791 |
manish.sha |
30 |
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 |
31 |
ORDER_TRACK_URL='http://www.shopclues.com/index.php?dispatch=order_lookup.details'
|
| 18086 |
manish.sha |
32 |
ORDER_TRACK_URL_DB='https://smo.shopclues.com/msgorderdetails?'
|
| 15509 |
manish.sha |
33 |
BASE_URL= 'http://www.shopclues.com'
|
|
|
34 |
BASE_MURL= 'http://m.shopclues.com'
|
|
|
35 |
|
|
|
36 |
class Store(MStore):
|
|
|
37 |
|
|
|
38 |
'''
|
|
|
39 |
This is to map order statuses of our system to order statuses of snapdeal.
|
|
|
40 |
And our statuses will change accordingly.
|
|
|
41 |
|
|
|
42 |
'''
|
|
|
43 |
OrderStatusMap = {
|
| 16272 |
manish.sha |
44 |
MStore.ORDER_PLACED : ['payment successful', 'new order - cod confirmation pending', 'processing', 'quality check','on schedule', 'processing - pickup initiated', 'processing - ready to dispatch','processing - procurement delay from merchant','processing - slight procurment delay from merchant','cod order confirmed by customer'],
|
| 19349 |
manish.sha |
45 |
MStore.ORDER_DELIVERED : ['delivered', 'complete', 'order delivered'],
|
| 16254 |
manish.sha |
46 |
MStore.ORDER_SHIPPED : ['in transit', 'dispatched','shipped','order handed to courier','order handed over to courier'],
|
| 16971 |
manish.sha |
47 |
MStore.ORDER_CANCELLED : ['payment failed', 'canceled', 'payment declined', 'order on hold - cancellation requested by customer', 'courier returned', 'canceled on customer request', 'canceled by customer','order canceled by customer','canceled - address not shippable','return complete','undelivered - returning to origin', 'canceled - shipment untraceable','order declined']
|
| 15509 |
manish.sha |
48 |
}
|
|
|
49 |
OrderStatusConfirmationMap= {
|
| 15791 |
manish.sha |
50 |
"P" : "Payment Successful",
|
|
|
51 |
"D" : "Order Declined",
|
|
|
52 |
"O" : "New Order - COD confirmation Pending"
|
| 15509 |
manish.sha |
53 |
}
|
|
|
54 |
|
|
|
55 |
CONF_CB_AMOUNT = MStore.CONF_CB_DISCOUNTED_PRICE
|
|
|
56 |
|
| 16111 |
manish.sha |
57 |
def __init__(self,store_id):
|
|
|
58 |
super(Store, self).__init__(store_id)
|
|
|
59 |
|
| 15791 |
manish.sha |
60 |
def convertToObj(self,offer):
|
| 16202 |
manish.sha |
61 |
orderRef = offer['MerchantRef']
|
|
|
62 |
if len(orderRef)>15:
|
|
|
63 |
orderRef = orderRef[0:len(orderRef)-10]
|
| 17249 |
manish.sha |
64 |
offer1 = ShopCluesAffiliateInfo(offer['UID'], offer['TransactionTime'], offer['TransactionID'], orderRef, orderRef, offer['Merchant'], offer['PID'], offer['Product'], float(str(offer['SR'])), float(str(offer['TransactionValue'])), offer['UKey'], offer['ClickTime'], offer['Status'])
|
| 15791 |
manish.sha |
65 |
return offer1
|
|
|
66 |
|
|
|
67 |
def _saveToAffiliate(self, offers):
|
|
|
68 |
collection = self.db.shopcluesOrderAffiliateInfo
|
|
|
69 |
mcollection = self.db.merchantOrder
|
|
|
70 |
for offerObj in offers:
|
|
|
71 |
offer = self.convertToObj(offerObj)
|
|
|
72 |
collection.update({"transactionId":offer.transactionId, "subTagId":offer.subTagId, "payOut":offer.payOut},{"$set":todict(offer)}, upsert=True)
|
|
|
73 |
mcollection.update({"subTagId":offer.subTagId, "storeId":self.store_id, "subOrders.missingAff":True}, {"$set":{"subOrders.$.missingAff":False}})
|
|
|
74 |
|
| 15940 |
manish.sha |
75 |
def scrapeAffiliate(self, startDate=datetime.today() - timedelta(days=10), endDate=datetime.today()):
|
| 15791 |
manish.sha |
76 |
uri = AFFLIATE_TRASACTIONS_URL%(startDate.year,startDate.month,startDate.day,endDate.year,endDate.month,endDate.day)
|
|
|
77 |
root = ET.parse(urllib2.urlopen(uri)).getroot()
|
|
|
78 |
if len(root)> 0 and len(root[0])> 0:
|
|
|
79 |
offers = []
|
|
|
80 |
for child in root[0][0]:
|
|
|
81 |
offers.append(child.attrib)
|
|
|
82 |
self._saveToAffiliate(offers)
|
|
|
83 |
|
| 15509 |
manish.sha |
84 |
def _setLastSaleDate(self, saleDate):
|
|
|
85 |
self.db.lastSaleDtate.update({'storeId':self.store_id}, {'$set':{'saleDate':saleDate}})
|
|
|
86 |
|
|
|
87 |
def getName(self):
|
|
|
88 |
return "shopclues"
|
|
|
89 |
|
|
|
90 |
def _getLastSaleDate(self,):
|
|
|
91 |
lastDaySaleObj = self.db.lastDaySale.find_one({"storeId":self.store_id})
|
|
|
92 |
if lastDaySaleObj is None:
|
|
|
93 |
return datetime.min
|
|
|
94 |
|
|
|
95 |
def _getStatusFromDetailedStatus(self, detailedStatus):
|
|
|
96 |
for key, value in Store.OrderStatusMap.iteritems():
|
|
|
97 |
if detailedStatus.lower() in value:
|
|
|
98 |
return key
|
|
|
99 |
print "Detailed Status need to be mapped", detailedStatus, self.store_id
|
|
|
100 |
return None
|
|
|
101 |
|
| 15791 |
manish.sha |
102 |
def _getSingleSubOrderMap(self, orderId, soup, orderObj):
|
|
|
103 |
orderStatus = self.OrderStatusConfirmationMap.get(orderObj['0']['status'])
|
| 16420 |
manish.sha |
104 |
statusTime= str(to_py_date(long(orderObj['0']['timestamp'])))
|
| 15509 |
manish.sha |
105 |
productDetailsMap = {}
|
| 16230 |
manish.sha |
106 |
orderTables = soup.body.findAll("table", {'class':'table product-list'})
|
|
|
107 |
orderTable = orderTables[len(orderTables)-1].findAll('tr', recursive=False)
|
| 15791 |
manish.sha |
108 |
firstRow = orderTable.pop(0)
|
| 15949 |
manish.sha |
109 |
totalColumns = len(firstRow.find_all('th'))
|
| 15791 |
manish.sha |
110 |
jsonSubOrdersMap = {}
|
|
|
111 |
count = 1
|
|
|
112 |
|
|
|
113 |
for val in orderObj['0']['items'].values():
|
|
|
114 |
newCount = 0
|
| 16110 |
manish.sha |
115 |
counts = []
|
| 15791 |
manish.sha |
116 |
for key in jsonSubOrdersMap.keys():
|
|
|
117 |
splitKey = key.split('-')
|
| 16112 |
manish.sha |
118 |
if orderObj['0']['is_parent_order'] == 'N':
|
|
|
119 |
if str(val['order_id']) == splitKey[0]:
|
|
|
120 |
counts.append(int(splitKey[1]))
|
|
|
121 |
else:
|
| 16420 |
manish.sha |
122 |
if val['child'] is None:
|
|
|
123 |
if str(val['order_id']) == splitKey[0]:
|
|
|
124 |
counts.append(int(splitKey[1]))
|
|
|
125 |
else:
|
|
|
126 |
if str(val['child']) == splitKey[0]:
|
|
|
127 |
counts.append(int(splitKey[1]))
|
| 16110 |
manish.sha |
128 |
|
|
|
129 |
if len(counts) >0:
|
|
|
130 |
newCount = max(counts)
|
| 16108 |
manish.sha |
131 |
count = newCount +1
|
| 16112 |
manish.sha |
132 |
if orderObj['0']['is_parent_order'] == 'N':
|
|
|
133 |
jsonSubOrdersMap[str(val['order_id'])+'-'+str(count)] = val
|
|
|
134 |
else:
|
| 16420 |
manish.sha |
135 |
if val['child'] is None:
|
|
|
136 |
jsonSubOrdersMap[str(val['order_id'])+'-'+str(count)] = val
|
|
|
137 |
else:
|
|
|
138 |
jsonSubOrdersMap[str(val['child'])+'-'+str(count)] = val
|
| 15791 |
manish.sha |
139 |
|
| 16110 |
manish.sha |
140 |
|
| 16275 |
manish.sha |
141 |
|
| 15941 |
manish.sha |
142 |
print jsonSubOrdersMap.items()
|
|
|
143 |
|
| 15791 |
manish.sha |
144 |
count = 1
|
| 15509 |
manish.sha |
145 |
for orderTr in orderTable:
|
| 15791 |
manish.sha |
146 |
productDetailsSubMap = None
|
|
|
147 |
productDetailsSubMap = {}
|
| 15509 |
manish.sha |
148 |
cols = orderTr.find_all('td')
|
|
|
149 |
product_details = cols[0].find_all('a')
|
|
|
150 |
#print product_details
|
|
|
151 |
productUrl = product_details[0].get('href')
|
|
|
152 |
productName = product_details[0].contents[0].strip()
|
|
|
153 |
quantity = int(cols[1].text.strip())
|
| 15980 |
manish.sha |
154 |
sellingPrice = long(cols[2].text.strip().replace("Rs.","").replace(',',''))
|
| 15791 |
manish.sha |
155 |
discount = 0
|
|
|
156 |
subtotal = 0
|
|
|
157 |
if totalColumns == 5:
|
| 15949 |
manish.sha |
158 |
if cols[3].text.strip()!='-' and 'Rs.' in cols[3].text.strip():
|
| 15980 |
manish.sha |
159 |
discount = long(cols[3].text.strip().replace("Rs.","").replace(',',''))
|
| 15791 |
manish.sha |
160 |
else:
|
|
|
161 |
discount = 0
|
| 15980 |
manish.sha |
162 |
subtotal = long(cols[4].text.strip().replace("Rs.","").replace(',',''))
|
| 17099 |
manish.sha |
163 |
elif totalColumns == 6:
|
|
|
164 |
if cols[3].text.strip()!='-' and 'Rs.' in cols[3].text.strip():
|
|
|
165 |
discount = long(cols[3].text.strip().replace("Rs.","").replace(',',''))
|
|
|
166 |
else:
|
|
|
167 |
discount = 0
|
|
|
168 |
subtotal = long(cols[5].text.strip().replace("Rs.","").replace(',',''))
|
| 15791 |
manish.sha |
169 |
else:
|
| 15980 |
manish.sha |
170 |
subtotal = long(cols[3].text.strip().replace("Rs.","").replace(',',''))
|
| 15509 |
manish.sha |
171 |
productDetailsSubMap['productUrl']=BASE_MURL+productUrl
|
|
|
172 |
productDetailsSubMap['productName']=productName
|
| 15791 |
manish.sha |
173 |
productDetailsSubMap['subOrderTrackingUrl']=ORDER_TRACK_URL_DB+'order_id=' +str(orderId)+'&email_id='+ orderObj['0']['email']
|
| 15509 |
manish.sha |
174 |
productDetailsSubMap['sellingPrice']=sellingPrice
|
|
|
175 |
productDetailsSubMap['quantity']=quantity
|
|
|
176 |
productDetailsSubMap['discount']=discount
|
|
|
177 |
productDetailsSubMap['subtotal']=subtotal
|
| 15942 |
manish.sha |
178 |
key = str(orderId)+'-'+str(count)
|
|
|
179 |
print 'SubOrder Map Key--',key
|
| 15791 |
manish.sha |
180 |
jsonSubOrderDetails = jsonSubOrdersMap.get(str(orderId)+'-'+str(count))
|
|
|
181 |
productCode = jsonSubOrderDetails['product_code']
|
|
|
182 |
productImgUrl = jsonSubOrderDetails['images']['image_path'][0]
|
| 15509 |
manish.sha |
183 |
productDetailsSubMap['productCode']=productCode
|
|
|
184 |
productDetailsSubMap['imgUrl']=productImgUrl
|
|
|
185 |
|
| 15791 |
manish.sha |
186 |
productDetailsSubMap['subOrderStatus']=orderStatus
|
|
|
187 |
productDetailsSubMap['subOrderStatusTime']=statusTime
|
|
|
188 |
productDetailsMap[str(orderId)+'-'+str(count)]=productDetailsSubMap
|
|
|
189 |
count = count +1
|
| 15509 |
manish.sha |
190 |
return productDetailsMap
|
|
|
191 |
|
| 15791 |
manish.sha |
192 |
def _getMultiSubOrdersMap(self, orderId, soup, orderObj):
|
| 16230 |
manish.sha |
193 |
orderTables = soup.body.findAll("table", {'class':'table product-list'})
|
|
|
194 |
orderTable = orderTables[len(orderTables)-1].findAll('tr', recursive=False)
|
| 16105 |
manish.sha |
195 |
firstRow = orderTable.pop(0)
|
| 15791 |
manish.sha |
196 |
#totalColumns = len(firstRow.find_all('td'))
|
| 15509 |
manish.sha |
197 |
productDetailsMap = {}
|
| 15791 |
manish.sha |
198 |
'''
|
|
|
199 |
jsonSubOrdersMap = {}
|
|
|
200 |
for val in orderObj['0']['items'].values():
|
|
|
201 |
jsonSubOrdersMap[val['order_id']] = val
|
|
|
202 |
'''
|
|
|
203 |
existingOrders = []
|
| 15509 |
manish.sha |
204 |
for orderTr in orderTable:
|
| 15791 |
manish.sha |
205 |
subOrderDetailsMap = {}
|
|
|
206 |
|
| 15509 |
manish.sha |
207 |
cols = orderTr.find_all('td')
|
|
|
208 |
product_details = cols[0].find_all('a')
|
|
|
209 |
#print product_details
|
|
|
210 |
subOrderId= product_details[1].contents[0].strip()
|
| 15791 |
manish.sha |
211 |
if subOrderId in existingOrders:
|
|
|
212 |
continue
|
|
|
213 |
else:
|
|
|
214 |
existingOrders.append(subOrderId)
|
|
|
215 |
#productUrl = product_details[0].get('href')
|
|
|
216 |
#productName = product_details[0].contents[0].strip()
|
|
|
217 |
subOrderTrackingParsingUrl = product_details[1].get('href')
|
|
|
218 |
#subOrderTrackingUrl = subOrderTrackingParsingUrl.split('order_lookup.details&')[1]
|
|
|
219 |
'''
|
| 15509 |
manish.sha |
220 |
quantity = int(cols[1].text.strip())
|
|
|
221 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
| 15791 |
manish.sha |
222 |
discount = 0
|
|
|
223 |
subtotal = 0
|
|
|
224 |
if totalColumns == 5:
|
|
|
225 |
if cols[3].text.strip()!='-' or 'Rs.' in cols[3].text.strip():
|
|
|
226 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
|
|
227 |
else:
|
|
|
228 |
discount = 0
|
|
|
229 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
|
|
230 |
else:
|
|
|
231 |
subtotal = long(cols[3].text.strip().replace("Rs.",""))
|
| 15509 |
manish.sha |
232 |
productDetailsSubMap['productUrl']=BASE_MURL+productUrl
|
|
|
233 |
productDetailsSubMap['productName']=productName
|
| 15791 |
manish.sha |
234 |
productDetailsSubMap['subOrderTrackingUrl']=ORDER_TRACK_URL_DB+subOrderTrackingUrl
|
| 15509 |
manish.sha |
235 |
productDetailsSubMap['sellingPrice']=sellingPrice
|
|
|
236 |
productDetailsSubMap['quantity']=quantity
|
|
|
237 |
productDetailsSubMap['discount']=discount
|
|
|
238 |
productDetailsSubMap['subtotal']=subtotal
|
| 15791 |
manish.sha |
239 |
jsonSubOrderDetails = jsonSubOrdersMap.get(subOrderId)
|
|
|
240 |
productCode = jsonSubOrderDetails['product_code']
|
|
|
241 |
productImgUrl = jsonSubOrderDetails['images']['image_path'][0]
|
| 15509 |
manish.sha |
242 |
productDetailsSubMap['productCode']=productCode
|
|
|
243 |
productDetailsSubMap['imgUrl']=productImgUrl
|
| 15791 |
manish.sha |
244 |
'''
|
| 16151 |
manish.sha |
245 |
orderTrackingPage = fetchResponseUsingProxy(BASE_URL+subOrderTrackingParsingUrl)
|
|
|
246 |
orderTrackingPageSoup = BeautifulSoup(orderTrackingPage)
|
| 15791 |
manish.sha |
247 |
'''
|
| 15509 |
manish.sha |
248 |
subOrderStatusList = orderTrackingPageSoup.findAll(attrs={'class' : 'price ord_status'})
|
|
|
249 |
subOrderStatus = subOrderStatusList[0].contents[0].strip()
|
|
|
250 |
subOrderStatusTime= orderTrackingPageSoup.findAll(attrs={'class' : 'sts no_mobile'})[1].contents[2].strip()
|
|
|
251 |
productDetailsSubMap['subOrderStatus'] = subOrderStatus
|
|
|
252 |
productDetailsSubMap['subOrderStatusTime'] = subOrderStatusTime
|
|
|
253 |
productDetailsSubMap['parentOrderId']=orderId
|
| 15791 |
manish.sha |
254 |
'''
|
|
|
255 |
|
|
|
256 |
subOrderDetailsMap = self._getSingleSubOrderMap(subOrderId, orderTrackingPageSoup, orderObj)
|
| 15509 |
manish.sha |
257 |
|
| 15791 |
manish.sha |
258 |
productDetailsMap = dict(productDetailsMap.items()+subOrderDetailsMap.items())
|
| 15509 |
manish.sha |
259 |
|
|
|
260 |
return productDetailsMap
|
|
|
261 |
|
|
|
262 |
def updateCashbackInSubOrders(self, subOrders):
|
|
|
263 |
for subOrder in subOrders:
|
|
|
264 |
cashbackStatus = Store.CB_NA
|
|
|
265 |
cashbackAmount = 0
|
|
|
266 |
percentage = 0
|
|
|
267 |
amount = subOrder.amountPaid
|
| 19524 |
manish.sha |
268 |
if subOrder.quantity>1:
|
|
|
269 |
amount = round(amount/subOrder.quantity, 0)
|
| 15509 |
manish.sha |
270 |
if amount > 0:
|
|
|
271 |
(cashbackAmount, percentage) = self.getCashbackAmount(subOrder.productCode, amount)
|
|
|
272 |
if cashbackAmount > 0:
|
|
|
273 |
cashbackStatus = Store.CB_PENDING
|
|
|
274 |
subOrder.cashBackStatus = cashbackStatus
|
| 19524 |
manish.sha |
275 |
subOrder.cashBackAmount = cashbackAmount*subOrder.quantity
|
| 15509 |
manish.sha |
276 |
subOrder.cashBackPercentage = percentage
|
|
|
277 |
return subOrders
|
| 16888 |
manish.sha |
278 |
|
|
|
279 |
def _parseSingleOrderUsingJsonWithoutItems(self, orderId, userId, subTagId, orderObj, orderSuccessUrl):
|
| 15509 |
manish.sha |
280 |
|
| 16888 |
manish.sha |
281 |
subOrders=[]
|
|
|
282 |
|
|
|
283 |
ordertotal = long(float(orderObj['0']['total']))
|
|
|
284 |
ordershippingcost = long(float(orderObj['0']['shipping_cost']))
|
|
|
285 |
subtotal = ordertotal-ordershippingcost
|
|
|
286 |
placedOn = str(orderObj['0']['last_update'])
|
|
|
287 |
totalDiscount = long(float(orderObj['0']['discount']))
|
|
|
288 |
totalOrdersAmount = (ordertotal + totalDiscount) - ordershippingcost
|
|
|
289 |
merchantOrderId = orderObj['0']['order_id']
|
|
|
290 |
promotionid = orderObj['0']['promotion_ids']
|
|
|
291 |
promotionObj = orderObj['0']['promotions'][promotionid]
|
|
|
292 |
productCode = str(promotionObj['bonuses'][0]['value'])
|
|
|
293 |
skuData = Mongo.getItemByMerchantIdentifier(productCode, 5)
|
|
|
294 |
|
|
|
295 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
|
|
|
296 |
merchantOrder.placedOn = placedOn
|
|
|
297 |
merchantOrder.merchantOrderId = str(merchantOrderId)
|
|
|
298 |
merchantOrder.paidAmount = ordertotal
|
|
|
299 |
|
|
|
300 |
|
|
|
301 |
if len(skuData)>0:
|
|
|
302 |
productUrl = BASE_MURL + str(urlparse(skuData.get('marketPlaceUrl')).path)
|
|
|
303 |
subOrder = SubOrder(skuData.get('product_name'), productUrl, placedOn, subtotal)
|
|
|
304 |
subOrder.merchantSubOrderId = str(merchantOrderId)+'-1'
|
|
|
305 |
subOrder.detailedStatus = Store.OrderStatusConfirmationMap.get(str(orderObj['0']['status']))
|
|
|
306 |
subOrder.imgUrl = skuData.get('thumbnail')
|
|
|
307 |
subOrder.offerDiscount = totalDiscount
|
|
|
308 |
subOrder.unitPrice = totalOrdersAmount
|
|
|
309 |
subOrder.productCode = productCode
|
|
|
310 |
subOrder.amountPaid = subtotal
|
|
|
311 |
subOrder.quantity = 1
|
|
|
312 |
subOrder.tracingkUrl = ORDER_TRACK_URL_DB + 'order_id=' +str(merchantOrderId)+'&email_id='+ str(orderObj['0']['email'])
|
|
|
313 |
dealRank = getDealRank(subOrder.productCode, self.store_id, merchantOrder.userId)
|
|
|
314 |
subOrder.dealRank = dealRank.get('rank')
|
|
|
315 |
subOrder.rankDesc = dealRank.get('description')
|
| 18384 |
amit.gupta |
316 |
subOrder.maxNlc = dealRank.get('maxNlc')
|
|
|
317 |
subOrder.minNlc = dealRank.get('minNlc')
|
|
|
318 |
subOrder.db = dealRank.get('dp')
|
|
|
319 |
subOrder.itemStatus = dealRank.get('status')
|
| 16888 |
manish.sha |
320 |
subOrders.append(subOrder)
|
|
|
321 |
else:
|
|
|
322 |
productSearch = fetchResponseUsingProxy(BASE_MURL+'/search?q='+productCode.strip())
|
|
|
323 |
productSearchResultPage = BeautifulSoup(productSearch)
|
|
|
324 |
productUrl = str(productSearchResultPage.find('a', {'class':'pd-list'})['href'])
|
|
|
325 |
style = productSearchResultPage.find('div', {'class':'pd-image'})['style']
|
|
|
326 |
imageurl = str(re.findall('url\(\"(.*?)\"\)', style)[0])
|
|
|
327 |
productName = str(productSearchResultPage.find('div', {'class':'pdt-name'}).text)
|
|
|
328 |
subOrder = SubOrder(productName, productUrl, placedOn, subtotal)
|
|
|
329 |
subOrder.merchantSubOrderId = str(merchantOrderId)+'-1'
|
|
|
330 |
subOrder.detailedStatus = Store.OrderStatusConfirmationMap.get(str(orderObj['0']['status']))
|
|
|
331 |
subOrder.imgUrl = imageurl
|
|
|
332 |
subOrder.offerDiscount = totalDiscount
|
|
|
333 |
subOrder.unitPrice = totalOrdersAmount
|
|
|
334 |
subOrder.productCode = productCode
|
|
|
335 |
subOrder.amountPaid = subtotal
|
|
|
336 |
subOrder.quantity = 1
|
|
|
337 |
subOrder.tracingkUrl = ORDER_TRACK_URL_DB + 'order_id=' +str(merchantOrderId)+'&email_id='+ str(orderObj['0']['email'])
|
|
|
338 |
dealRank = getDealRank(subOrder.productCode, self.store_id, merchantOrder.userId)
|
|
|
339 |
subOrder.dealRank = 0
|
|
|
340 |
subOrder.rankDesc = 'Not Applicable'
|
|
|
341 |
subOrders.append(subOrder)
|
|
|
342 |
|
|
|
343 |
merchantOrder.totalAmount = totalOrdersAmount
|
|
|
344 |
merchantOrder.discountApplied = totalDiscount
|
|
|
345 |
merchantOrder.deliveryCharges = ordershippingcost
|
|
|
346 |
merchantOrder.subOrders = self.updateCashbackInSubOrders(subOrders)
|
|
|
347 |
|
|
|
348 |
return merchantOrder
|
|
|
349 |
|
|
|
350 |
def _parseMultiOrderUsingJsonWithoutItems(self, orderId, userId, subTagId, orderObj, orderSuccessUrl):
|
|
|
351 |
pass
|
|
|
352 |
'''
|
|
|
353 |
subOrders=[]
|
|
|
354 |
|
|
|
355 |
ordertotal = long(float(orderObj['0']['total']))
|
|
|
356 |
ordershippingcost = long(float(orderObj['0']['shipping_cost']))
|
|
|
357 |
subtotal = ordertotal-ordershippingcost
|
|
|
358 |
placedOn = str(orderObj['0']['last_update'])
|
|
|
359 |
totalDiscount = long(float(orderObj['0']['discount']))
|
|
|
360 |
totalOrdersAmount = (ordertotal + totalDiscount) - ordershippingcost
|
|
|
361 |
merchantOrderId = orderObj['0']['order_id']
|
|
|
362 |
promotionids = orderObj['0']['promotion_ids'].split(',')
|
|
|
363 |
promotions = orderObj['0']['promotions']
|
|
|
364 |
|
|
|
365 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
|
|
|
366 |
merchantOrder.placedOn = placedOn
|
|
|
367 |
merchantOrder.merchantOrderId = str(merchantOrderId)
|
|
|
368 |
merchantOrder.paidAmount = ordertotal
|
|
|
369 |
|
|
|
370 |
|
|
|
371 |
for promotionId in promotionids:
|
|
|
372 |
promotion = promotions[promotionId]
|
|
|
373 |
productCode = str(promotion['bonuses'][0]['value'])
|
|
|
374 |
skuData = Mongo.getItemByMerchantIdentifier(productCode, 5)
|
|
|
375 |
|
|
|
376 |
|
|
|
377 |
return None
|
|
|
378 |
'''
|
|
|
379 |
|
| 15947 |
manish.sha |
380 |
def _parseOrders(self, orderId, mpOrderId, subTagId, userId, page, orderSuccessUrl, orderObj):
|
| 15509 |
manish.sha |
381 |
soup = BeautifulSoup(page)
|
|
|
382 |
productDetailsMap = {}
|
|
|
383 |
paymentFields = soup.findAll(attrs={'class' : 'box_paymentcalculations_row'})
|
|
|
384 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
| 15948 |
manish.sha |
385 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace("\r","").replace(" ","")
|
| 15509 |
manish.sha |
386 |
ordersubtotal=0
|
|
|
387 |
ordercluebucks=0
|
|
|
388 |
ordershippingcost=0
|
|
|
389 |
ordertotal=0
|
|
|
390 |
|
|
|
391 |
for val in paymentFields:
|
|
|
392 |
for value in val.contents:
|
|
|
393 |
if value is not None:
|
|
|
394 |
if 'div' in str(value).strip():
|
|
|
395 |
if 'Subtotal' in value.text.strip():
|
| 15981 |
manish.sha |
396 |
ordersubtotal = long(val.contents[3].text.strip().replace("Rs.","").replace(',',''))
|
| 16165 |
manish.sha |
397 |
print 'Order SubTotal:- ',ordersubtotal
|
| 15509 |
manish.sha |
398 |
if 'Shipping Cost' in value.text.strip():
|
| 15981 |
manish.sha |
399 |
ordershippingcost = long(val.contents[3].text.strip().replace("Rs.","").replace(',',''))
|
| 16165 |
manish.sha |
400 |
print 'Shipping Cost:- ',ordershippingcost
|
| 15509 |
manish.sha |
401 |
if 'Clue' in value.text.strip():
|
| 15981 |
manish.sha |
402 |
ordercluebucks = long(val.contents[3].text.strip().replace("Rs.","").replace(',',''))
|
| 16165 |
manish.sha |
403 |
print 'Clue bucks:- ',ordercluebucks
|
| 15509 |
manish.sha |
404 |
if 'Total' in value.text.strip():
|
| 15791 |
manish.sha |
405 |
ordertotal = val.contents[3].text.strip().replace("Rs.","")
|
|
|
406 |
ordertotal = ordertotal.replace(',','')
|
| 16165 |
manish.sha |
407 |
print 'Order Total:- ',ordertotal
|
| 15791 |
manish.sha |
408 |
|
|
|
409 |
if orderObj['0']['is_parent_order'] == 'N':
|
| 15947 |
manish.sha |
410 |
productDetailsMap = self._getSingleSubOrderMap(mpOrderId, soup, orderObj)
|
| 15509 |
manish.sha |
411 |
else:
|
| 16420 |
manish.sha |
412 |
if orderObj['0']['items'].values()[0]['child'] is None:
|
|
|
413 |
productDetailsMap = self._getSingleSubOrderMap(mpOrderId, soup, orderObj)
|
|
|
414 |
else:
|
|
|
415 |
productDetailsMap = self._getMultiSubOrdersMap(mpOrderId, soup, orderObj)
|
| 15509 |
manish.sha |
416 |
|
| 15791 |
manish.sha |
417 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
|
| 15509 |
manish.sha |
418 |
merchantOrder.placedOn = placedOn
|
| 15791 |
manish.sha |
419 |
merchantOrder.merchantOrderId = orderObj['0']['order_id']
|
| 15509 |
manish.sha |
420 |
merchantOrder.paidAmount = ordertotal
|
|
|
421 |
totalOrdersAmount = 0
|
|
|
422 |
totalDiscount = 0
|
|
|
423 |
subOrders= []
|
| 16281 |
manish.sha |
424 |
if len(productDetailsMap)==0:
|
|
|
425 |
print 'Unable to get Sub Orders for Now:- ',orderObj['0']['order_id']
|
| 15509 |
manish.sha |
426 |
for key in productDetailsMap:
|
|
|
427 |
subOrderDetail = productDetailsMap.get(key)
|
|
|
428 |
totalOrdersAmount = totalOrdersAmount + (subOrderDetail['sellingPrice'] * subOrderDetail['quantity'])
|
|
|
429 |
totalDiscount = totalDiscount + (subOrderDetail['discount'] * subOrderDetail['quantity'])
|
|
|
430 |
subOrder = SubOrder(subOrderDetail['productName'], subOrderDetail['productUrl'], placedOn, subOrderDetail['subtotal'])
|
|
|
431 |
subOrder.merchantSubOrderId = key
|
|
|
432 |
subOrder.detailedStatus = subOrderDetail['subOrderStatus']
|
|
|
433 |
subOrder.imgUrl = subOrderDetail['imgUrl']
|
|
|
434 |
subOrder.offerDiscount = subOrderDetail['discount'] * subOrderDetail['quantity']
|
|
|
435 |
subOrder.unitPrice = subOrderDetail['sellingPrice']
|
|
|
436 |
subOrder.productCode = subOrderDetail['productCode']
|
|
|
437 |
subOrder.amountPaid = subOrderDetail['subtotal']
|
|
|
438 |
subOrder.quantity = subOrderDetail['quantity']
|
| 15791 |
manish.sha |
439 |
subOrder.tracingkUrl = subOrderDetail['subOrderTrackingUrl']
|
| 16097 |
manish.sha |
440 |
dealRank = getDealRank(subOrder.productCode, self.store_id, merchantOrder.userId)
|
|
|
441 |
subOrder.dealRank = dealRank.get('rank')
|
|
|
442 |
subOrder.rankDesc = dealRank.get('description')
|
| 16283 |
amit.gupta |
443 |
subOrder.maxNlc = dealRank.get('maxNlc')
|
|
|
444 |
subOrder.minNlc = dealRank.get('minNlc')
|
|
|
445 |
subOrder.db = dealRank.get('dp')
|
|
|
446 |
subOrder.itemStatus = dealRank.get('status')
|
| 15509 |
manish.sha |
447 |
subOrders.append(subOrder)
|
|
|
448 |
merchantOrder.totalAmount = totalOrdersAmount
|
|
|
449 |
merchantOrder.discountApplied = totalDiscount
|
|
|
450 |
merchantOrder.deliveryCharges = ordershippingcost
|
|
|
451 |
merchantOrder.subOrders = self.updateCashbackInSubOrders(subOrders)
|
|
|
452 |
|
|
|
453 |
return merchantOrder
|
|
|
454 |
|
|
|
455 |
def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
|
|
|
456 |
resp = {}
|
|
|
457 |
try:
|
| 20002 |
kshitij.so |
458 |
dummySoup = BeautifulSoup(rawHtml)
|
|
|
459 |
orderIdSpan = dummySoup.find('div',{'class':'description'}).find('span').text
|
|
|
460 |
temp_order_id = re.findall('\d+', orderIdSpan)[0]
|
|
|
461 |
login_url = "https://smo.shopclues.com/login"
|
|
|
462 |
br_temp = login(login_url)
|
|
|
463 |
orderDetailPage = br_temp.open("https://smo.shopclues.com/orderconfirmation?order_id="+str(temp_order_id)+"&status=P")
|
|
|
464 |
orderDetailPage = ungzipResponse(orderDetailPage)
|
|
|
465 |
rawHtmlSoup = BeautifulSoup(orderDetailPage)
|
|
|
466 |
br_temp.open("https://smo.shopclues.com/logout")
|
| 15791 |
manish.sha |
467 |
emailId = None
|
|
|
468 |
orderObj = None
|
|
|
469 |
merchantOrderId = None
|
|
|
470 |
for script in rawHtmlSoup.find_all('script'):
|
|
|
471 |
if 'orderConfirmation' in script.text:
|
| 18086 |
manish.sha |
472 |
orderStr = script.text.strip().split('\n')[0].split('orderConfirmation = ')[1]
|
| 20002 |
kshitij.so |
473 |
orderStr = orderStr[:-2]
|
| 18086 |
manish.sha |
474 |
orderObj = json.loads(orderStr)
|
| 15791 |
manish.sha |
475 |
if merchantOrderId is None:
|
|
|
476 |
merchantOrderId = orderObj['0']['order_id']
|
|
|
477 |
emailId = orderObj['0']['email']
|
| 16197 |
manish.sha |
478 |
if orderObj is None or merchantOrderId is None:
|
| 16226 |
manish.sha |
479 |
orderIdDiv = rawHtmlSoup.body.find("div", {'class':'conf_succes'})
|
|
|
480 |
if orderIdDiv is None:
|
|
|
481 |
orderIdArt = rawHtmlSoup.body.find("article", {'class':'white'})
|
|
|
482 |
if orderIdArt is None:
|
| 18062 |
manish.sha |
483 |
otpInput = rawHtmlSoup.body.find("input", {'id':'cod_otp'})
|
|
|
484 |
if otpInput is None:
|
|
|
485 |
resp['result'] = 'ORDER_NOT_CREATED_UNKNOWN'
|
|
|
486 |
return resp
|
|
|
487 |
else:
|
|
|
488 |
resp['result'] = 'ORDER_IGNORED_OTP'
|
|
|
489 |
return resp
|
| 16226 |
manish.sha |
490 |
else:
|
|
|
491 |
orderIdDiv= orderIdArt.find('p', recursive=False)
|
|
|
492 |
orderIdVal = str(orderIdDiv.text.split(' : ')[1])
|
|
|
493 |
print "Opening Shopclues Login Page"
|
| 18086 |
manish.sha |
494 |
login_url = "https://smo.shopclues.com/login"
|
| 16226 |
manish.sha |
495 |
br1 = login(login_url)
|
| 18086 |
manish.sha |
496 |
orderDetailPage = br1.open("https://smo.shopclues.com/orderconfirmation?order_id="+orderIdVal+"&status=P")
|
| 16226 |
manish.sha |
497 |
orderDetailPage = ungzipResponse(orderDetailPage)
|
|
|
498 |
rawHtmlSoup = BeautifulSoup(orderDetailPage)
|
|
|
499 |
for script in rawHtmlSoup.find_all('script'):
|
|
|
500 |
if 'orderConfirmation' in script.text:
|
|
|
501 |
orderObj = json.loads(script.text.strip().split('\n')[0].split('orderConfirmation = ')[1].split(';')[0])
|
|
|
502 |
if merchantOrderId is None:
|
|
|
503 |
merchantOrderId = orderObj['0']['order_id']
|
|
|
504 |
emailId = orderObj['0']['email']
|
| 18086 |
manish.sha |
505 |
logoutpage = br1.open("https://smo.shopclues.com/logout")
|
| 16226 |
manish.sha |
506 |
print br1.geturl()
|
|
|
507 |
else:
|
|
|
508 |
orderIdDiv= orderIdDiv.find('div', recursive=False)
|
|
|
509 |
orderIdVal = str(orderIdDiv.span.text)
|
|
|
510 |
print "Opening Shopclues Login Page"
|
| 18086 |
manish.sha |
511 |
login_url = "https://smo.shopclues.com/login"
|
| 16226 |
manish.sha |
512 |
br1 = login(login_url)
|
| 18086 |
manish.sha |
513 |
orderDetailPage = br1.open("https://smo.shopclues.com/orderconfirmation?order_id="+orderIdVal+"&status=P")
|
| 16226 |
manish.sha |
514 |
orderDetailPage = ungzipResponse(orderDetailPage)
|
|
|
515 |
rawHtmlSoup = BeautifulSoup(orderDetailPage)
|
|
|
516 |
for script in rawHtmlSoup.find_all('script'):
|
|
|
517 |
if 'orderConfirmation' in script.text:
|
|
|
518 |
orderObj = json.loads(script.text.strip().split('\n')[0].split('orderConfirmation = ')[1].split(';')[0])
|
|
|
519 |
if merchantOrderId is None:
|
|
|
520 |
merchantOrderId = orderObj['0']['order_id']
|
|
|
521 |
emailId = orderObj['0']['email']
|
| 18086 |
manish.sha |
522 |
logoutpage = br1.open("https://smo.shopclues.com/logout")
|
| 16226 |
manish.sha |
523 |
print br1.geturl()
|
|
|
524 |
|
| 16275 |
manish.sha |
525 |
if type(orderObj['0']['items']) is list:
|
|
|
526 |
print "Opening Shopclues Login Page"
|
| 18086 |
manish.sha |
527 |
login_url = "https://smo.shopclues.com/login"
|
| 16275 |
manish.sha |
528 |
br1 = login(login_url)
|
| 18086 |
manish.sha |
529 |
orderDetailPage = br1.open("https://smo.shopclues.com/orderconfirmation?order_id="+str(merchantOrderId)+"&status=P")
|
| 16275 |
manish.sha |
530 |
orderDetailPage = ungzipResponse(orderDetailPage)
|
|
|
531 |
rawHtmlSoup = BeautifulSoup(orderDetailPage)
|
|
|
532 |
for script in rawHtmlSoup.find_all('script'):
|
|
|
533 |
if 'orderConfirmation' in script.text:
|
|
|
534 |
orderObj = json.loads(script.text.strip().split('\n')[0].split('orderConfirmation = ')[1].split(';')[0])
|
|
|
535 |
if merchantOrderId is None:
|
|
|
536 |
merchantOrderId = orderObj['0']['order_id']
|
|
|
537 |
emailId = orderObj['0']['email']
|
| 18086 |
manish.sha |
538 |
logoutpage = br1.open("https://smo.shopclues.com/logout")
|
| 16275 |
manish.sha |
539 |
print br1.geturl()
|
|
|
540 |
|
| 15509 |
manish.sha |
541 |
br = getBrowserObject()
|
| 15791 |
manish.sha |
542 |
url = ORDER_TRACK_URL +'&order_id=' +str(merchantOrderId)+'&email_id='+ emailId
|
| 15509 |
manish.sha |
543 |
page = br.open(url)
|
| 16889 |
manish.sha |
544 |
print 'Track Order Url ', br.geturl()
|
| 16890 |
manish.sha |
545 |
if type(orderObj['0']['items']) is list:
|
|
|
546 |
if len(orderObj['0']['promotions'])==1:
|
|
|
547 |
merchantOrder = self._parseSingleOrderUsingJsonWithoutItems(orderId, userId, subTagId, orderObj, orderSuccessUrl)
|
|
|
548 |
merchantOrder.orderTrackingUrl = ORDER_TRACK_URL_DB + 'order_id=' +str(merchantOrderId)+'&email_id='+ emailId
|
|
|
549 |
if self._saveToOrder(todict(merchantOrder)):
|
|
|
550 |
resp['result'] = 'ORDER_CREATED'
|
|
|
551 |
return resp
|
|
|
552 |
else:
|
|
|
553 |
resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
|
|
|
554 |
return resp
|
| 16888 |
manish.sha |
555 |
'''
|
|
|
556 |
else:
|
|
|
557 |
resp['result'] = 'ORDER_NOT_CREATED_KNOWN'
|
|
|
558 |
return resp
|
|
|
559 |
|
|
|
560 |
elif len(orderObj['0']['promotions'])>1:
|
|
|
561 |
merchantOrder = self._parseMultiOrderUsingJsonWithoutItems(orderId, userId, subTagId, orderObj, orderSuccessUrl)
|
|
|
562 |
'''
|
|
|
563 |
|
| 15509 |
manish.sha |
564 |
headers = str(page.info()).split('\n')
|
|
|
565 |
page = ungzipResponse(page)
|
|
|
566 |
jsonResponse = None
|
|
|
567 |
for header in headers:
|
|
|
568 |
header = header.split(':')
|
|
|
569 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
|
|
570 |
jsonResponse = json.loads(page)
|
|
|
571 |
if jsonResponse is not None:
|
|
|
572 |
page = jsonResponse['text']
|
|
|
573 |
|
| 16370 |
manish.sha |
574 |
merchantOrder = self._parseOrders(orderId, merchantOrderId, subTagId, userId, page, orderSuccessUrl, orderObj)
|
| 15509 |
manish.sha |
575 |
|
| 15948 |
manish.sha |
576 |
merchantOrder.orderTrackingUrl = ORDER_TRACK_URL_DB + 'order_id=' +str(merchantOrderId)+'&email_id='+ emailId
|
| 15509 |
manish.sha |
577 |
|
|
|
578 |
if self._saveToOrder(todict(merchantOrder)):
|
|
|
579 |
resp['result'] = 'ORDER_CREATED'
|
|
|
580 |
else:
|
|
|
581 |
resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
|
|
|
582 |
|
|
|
583 |
return resp
|
|
|
584 |
except:
|
|
|
585 |
print "Error occurred"
|
|
|
586 |
traceback.print_exc()
|
|
|
587 |
resp['result'] = 'ORDER_NOT_CREATED'
|
| 16120 |
manish.sha |
588 |
return resp
|
| 15509 |
manish.sha |
589 |
|
| 15791 |
manish.sha |
590 |
def parseSingleSubOrder(self, soup, emailId, subOrderId):
|
|
|
591 |
orderStatusList = soup.findAll(attrs={'class' : 'price ord_status'})
|
|
|
592 |
subOrderStatus = orderStatusList[0].contents[0].strip()
|
| 15509 |
manish.sha |
593 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
| 16230 |
manish.sha |
594 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace("\r","").replace(" ","")
|
|
|
595 |
orderTables = soup.body.findAll("table", {'class':'table product-list'})
|
|
|
596 |
orderTable = orderTables[len(orderTables)-1].findAll('tr', recursive=False)
|
| 15791 |
manish.sha |
597 |
firstRow = orderTable.pop(0)
|
| 15949 |
manish.sha |
598 |
totalColumns = len(firstRow.find_all('th'))
|
| 15791 |
manish.sha |
599 |
subOrders =[]
|
|
|
600 |
count =1
|
| 15509 |
manish.sha |
601 |
for orderTr in orderTable:
|
|
|
602 |
cols = orderTr.find_all('td')
|
|
|
603 |
product_details = cols[0].find_all('a')
|
|
|
604 |
#print product_details
|
|
|
605 |
productUrl = product_details[0].get('href')
|
|
|
606 |
productName = product_details[0].contents[0].strip()
|
|
|
607 |
quantity = int(cols[1].text.strip())
|
| 15980 |
manish.sha |
608 |
sellingPrice = long(cols[2].text.strip().replace("Rs.","").replace(',',''))
|
| 15791 |
manish.sha |
609 |
discount = 0
|
|
|
610 |
subtotal = 0
|
|
|
611 |
if totalColumns == 5:
|
| 15949 |
manish.sha |
612 |
if cols[3].text.strip()!='-' and 'Rs.' in cols[3].text.strip():
|
| 15980 |
manish.sha |
613 |
discount = long(cols[3].text.strip().replace("Rs.","").replace(',',''))
|
| 15791 |
manish.sha |
614 |
else:
|
|
|
615 |
discount = 0
|
| 15980 |
manish.sha |
616 |
subtotal = long(cols[4].text.strip().replace("Rs.","").replace(',',''))
|
| 17100 |
manish.sha |
617 |
elif totalColumns == 6:
|
|
|
618 |
if cols[3].text.strip()!='-' and 'Rs.' in cols[3].text.strip():
|
|
|
619 |
discount = long(cols[3].text.strip().replace("Rs.","").replace(',',''))
|
|
|
620 |
else:
|
|
|
621 |
discount = 0
|
|
|
622 |
subtotal = long(cols[5].text.strip().replace("Rs.","").replace(',',''))
|
| 15791 |
manish.sha |
623 |
else:
|
| 15980 |
manish.sha |
624 |
subtotal = long(cols[3].text.strip().replace("Rs.","").replace(',',''))
|
| 16151 |
manish.sha |
625 |
productPage = fetchResponseUsingProxy(BASE_MURL+productUrl)
|
|
|
626 |
productPageSoup = BeautifulSoup(productPage)
|
| 15791 |
manish.sha |
627 |
productCode = productPageSoup.find('input', {'type':'hidden'})['value']
|
| 15509 |
manish.sha |
628 |
allproductImageTags = productPageSoup.findAll(attrs={'class' : 'pd-image'})
|
|
|
629 |
productImgUrl = ''
|
|
|
630 |
if allproductImageTags is not None and len(allproductImageTags)>0:
|
|
|
631 |
productImgUrl= allproductImageTags[0].get('style').split("background:url('")[1].split("')no-repeat center")[0].strip()
|
|
|
632 |
|
|
|
633 |
subOrder = SubOrder(productName, productUrl, placedOn, subtotal)
|
| 15791 |
manish.sha |
634 |
subOrder.merchantSubOrderId = str(subOrderId)+'-'+str(count)
|
| 15509 |
manish.sha |
635 |
subOrder.detailedStatus = subOrderStatus
|
|
|
636 |
subOrder.imgUrl = productImgUrl
|
|
|
637 |
subOrder.offerDiscount = discount*quantity
|
|
|
638 |
subOrder.unitPrice = sellingPrice
|
|
|
639 |
subOrder.productCode = productCode
|
|
|
640 |
subOrder.amountPaid = subtotal
|
|
|
641 |
subOrder.quantity = quantity
|
| 15791 |
manish.sha |
642 |
subOrder.tracingkUrl = ORDER_TRACK_URL_DB + 'order_id=' +subOrderId+'&email_id='+ emailId
|
| 15509 |
manish.sha |
643 |
subOrders.append(subOrder)
|
| 15791 |
manish.sha |
644 |
count = count +1
|
| 15509 |
manish.sha |
645 |
|
|
|
646 |
subOrders = self.updateCashbackInSubOrders(subOrders)
|
| 15791 |
manish.sha |
647 |
return subOrders
|
| 15509 |
manish.sha |
648 |
|
| 15791 |
manish.sha |
649 |
def parseMultiSubOrders(self, soup, emailId):
|
| 16230 |
manish.sha |
650 |
orderTables = soup.body.findAll("table", {'class':'table product-list'})
|
|
|
651 |
orderTable = orderTables[len(orderTables)-1].findAll('tr', recursive=False)
|
| 16145 |
manish.sha |
652 |
firstRow = orderTable.pop(0)
|
| 15791 |
manish.sha |
653 |
'''
|
|
|
654 |
totalColumns = len(firstRow.find_all('td'))
|
|
|
655 |
|
| 15509 |
manish.sha |
656 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
| 15791 |
manish.sha |
657 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace(" ","")
|
|
|
658 |
'''
|
| 15509 |
manish.sha |
659 |
subOrders = []
|
| 15791 |
manish.sha |
660 |
existingOrders = []
|
| 15509 |
manish.sha |
661 |
for orderTr in orderTable:
|
|
|
662 |
cols = orderTr.find_all('td')
|
|
|
663 |
product_details = cols[0].find_all('a')
|
|
|
664 |
#print product_details
|
|
|
665 |
subOrderId= product_details[1].contents[0].strip()
|
| 15791 |
manish.sha |
666 |
if subOrderId in existingOrders:
|
|
|
667 |
continue
|
|
|
668 |
else:
|
|
|
669 |
existingOrders.append(subOrderId)
|
|
|
670 |
'''
|
| 15509 |
manish.sha |
671 |
productUrl = product_details[0].get('href')
|
|
|
672 |
productName = product_details[0].contents[0].strip()
|
| 15791 |
manish.sha |
673 |
'''
|
|
|
674 |
subOrderTrackingParsingUrl = product_details[1].get('href')
|
|
|
675 |
#subOrderTrackingUrl = subOrderTrackingParsingUrl.split('order_lookup.details&')[1]
|
|
|
676 |
'''
|
| 15509 |
manish.sha |
677 |
quantity = int(cols[1].text.strip())
|
|
|
678 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
| 15791 |
manish.sha |
679 |
discount = 0
|
|
|
680 |
subtotal = 0
|
|
|
681 |
if totalColumns == 5:
|
|
|
682 |
if cols[3].text.strip()!='-' or 'Rs.' in cols[3].text.strip():
|
|
|
683 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
|
|
684 |
else:
|
|
|
685 |
discount = 0
|
|
|
686 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
|
|
687 |
else:
|
|
|
688 |
subtotal = long(cols[3].text.strip().replace("Rs.",""))
|
|
|
689 |
|
| 15509 |
manish.sha |
690 |
br = getBrowserObject()
|
|
|
691 |
productPage = br.open(BASE_MURL+productUrl)
|
|
|
692 |
productPageHeaders = str(productPage.info()).split('\n')
|
|
|
693 |
productPage = ungzipResponse(productPage)
|
|
|
694 |
jsonProductResponse = None
|
|
|
695 |
for header in productPageHeaders:
|
|
|
696 |
header = header.split(':')
|
|
|
697 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
|
|
698 |
jsonProductResponse = json.loads(productPage)
|
|
|
699 |
productPageSoup= None
|
|
|
700 |
if jsonProductResponse is not None:
|
|
|
701 |
productPageSoup = BeautifulSoup(jsonProductResponse['text'])
|
|
|
702 |
else:
|
|
|
703 |
productPageSoup = BeautifulSoup(productPage)
|
| 15791 |
manish.sha |
704 |
productCode = productPageSoup.find('input', {'type':'hidden'})['value']
|
| 15509 |
manish.sha |
705 |
allproductImageTags = productPageSoup.findAll(attrs={'class' : 'pd-image'})
|
|
|
706 |
productImgUrl = ''
|
|
|
707 |
if allproductImageTags is not None and len(allproductImageTags)>0:
|
|
|
708 |
productImgUrl= allproductImageTags[0].get('style').split("background:url('")[1].split("')no-repeat center")[0].strip()
|
|
|
709 |
productDetailsSubMap['productCode']=productCode
|
|
|
710 |
productDetailsSubMap['imgUrl']=productImgUrl
|
| 15791 |
manish.sha |
711 |
'''
|
| 16151 |
manish.sha |
712 |
orderTrackingPage = fetchResponseUsingProxy(BASE_URL+subOrderTrackingParsingUrl)
|
|
|
713 |
orderTrackingPageSoup = BeautifulSoup(orderTrackingPage)
|
| 15791 |
manish.sha |
714 |
subOrdersDetails = self.parseSingleSubOrder(orderTrackingPageSoup, emailId, subOrderId)
|
|
|
715 |
subOrders = list(set(subOrders + subOrdersDetails))
|
| 15509 |
manish.sha |
716 |
|
| 15791 |
manish.sha |
717 |
return subOrders
|
| 15509 |
manish.sha |
718 |
|
|
|
719 |
def scrapeStoreOrders(self,):
|
|
|
720 |
#collectionMap = {'palcedOn':1}
|
|
|
721 |
searchMap = {}
|
|
|
722 |
collectionMap = {"orderTrackingUrl":1}
|
|
|
723 |
orders = self._getActiveOrders(searchMap,collectionMap)
|
|
|
724 |
for order in orders:
|
|
|
725 |
print "Order", self.store_name, order['orderId'], order['orderTrackingUrl']
|
| 18575 |
manish.sha |
726 |
url = ORDER_TRACK_URL
|
|
|
727 |
if 'trackOrder' in order['orderTrackingUrl']:
|
|
|
728 |
url = url +'&'+ order['orderTrackingUrl'].split('trackOrder?')[1]
|
|
|
729 |
else:
|
|
|
730 |
url = url +'&'+ order['orderTrackingUrl'].split('msgorderdetails?')[1]
|
| 16141 |
manish.sha |
731 |
print url
|
| 16249 |
manish.sha |
732 |
page = None
|
|
|
733 |
retry = 1
|
|
|
734 |
while retry <=3:
|
|
|
735 |
try:
|
|
|
736 |
page = fetchResponseUsingProxy(url)
|
|
|
737 |
break
|
|
|
738 |
except:
|
| 16250 |
manish.sha |
739 |
traceback.print_exc()
|
| 16249 |
manish.sha |
740 |
retry = retry + 1
|
|
|
741 |
|
| 15509 |
manish.sha |
742 |
soup = BeautifulSoup(page)
|
|
|
743 |
bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
|
|
744 |
closed = True
|
| 16144 |
manish.sha |
745 |
orderIdSpan = soup.body.find("span", {'class':'price ord_no'})
|
|
|
746 |
if orderIdSpan is not None:
|
| 16143 |
manish.sha |
747 |
orderStatusList = soup.findAll(attrs={'class' : 'price ord_status'})
|
|
|
748 |
if orderStatusList is not None and len(orderStatusList)>0:
|
|
|
749 |
subOrderId = soup.findAll(attrs={'class':'price ord_no'})[0].text.strip()
|
|
|
750 |
orderStatus = orderStatusList[0].contents[0].strip()
|
| 16230 |
manish.sha |
751 |
orderTables = soup.body.findAll("table", {'class':'table product-list'})
|
| 16229 |
manish.sha |
752 |
orderTable = orderTables[len(orderTables)-1].findAll('tr', recursive=False)
|
| 16143 |
manish.sha |
753 |
orderTable.pop(0)
|
|
|
754 |
count = 1
|
|
|
755 |
while count <= len(orderTable):
|
| 16160 |
manish.sha |
756 |
subbulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
| 16152 |
manish.sha |
757 |
print 'Sub Order Id', str(subOrderId)+'-'+str(count)
|
| 16143 |
manish.sha |
758 |
subOrder = self._isSubOrderActive(order, str(subOrderId)+'-'+str(count))
|
|
|
759 |
if subOrder is None:
|
|
|
760 |
try:
|
| 16787 |
manish.sha |
761 |
print 'Email Id:- '+ str(order['orderTrackingUrl'].split('email_id=')[1])+' and Order Id:- ' + str(subOrderId)
|
| 16143 |
manish.sha |
762 |
subOrders = self.parseSingleSubOrder(soup, order['orderTrackingUrl'].split('email_id=')[1], subOrderId)
|
|
|
763 |
for subOrder in subOrders:
|
|
|
764 |
if subOrder is None:
|
|
|
765 |
continue
|
|
|
766 |
self.db.merchantOrder.update({"orderId":order['orderId']},{'$push':{"subOrders":{"$each":todict([subOrder])}}})
|
|
|
767 |
print "Added new suborders to Order id - ", order['orderId']
|
|
|
768 |
closed = False
|
|
|
769 |
except:
|
| 16227 |
manish.sha |
770 |
traceback.print_exc()
|
| 16143 |
manish.sha |
771 |
pass
|
| 16227 |
manish.sha |
772 |
count = count+1
|
| 16143 |
manish.sha |
773 |
continue
|
|
|
774 |
elif subOrder['closed']:
|
| 16226 |
manish.sha |
775 |
count = count+1
|
| 16143 |
manish.sha |
776 |
continue
|
|
|
777 |
else:
|
| 16163 |
manish.sha |
778 |
findMap = {"orderId": order['orderId'], "subOrders.merchantSubOrderId": str(subOrderId)+'-'+str(count)}
|
| 16143 |
manish.sha |
779 |
updateMap = {}
|
|
|
780 |
updateMap["subOrders.$.detailedStatus"] = orderStatus
|
|
|
781 |
status = self._getStatusFromDetailedStatus(orderStatus)
|
|
|
782 |
closedStatus = status in [Store.ORDER_DELIVERED, Store.ORDER_CANCELLED]
|
|
|
783 |
if status is not None:
|
|
|
784 |
updateMap["subOrders.$.status"] = status
|
|
|
785 |
if closedStatus:
|
|
|
786 |
#if status is closed then change the paybackStatus accordingly
|
| 16155 |
manish.sha |
787 |
print 'Order Closed'
|
| 16143 |
manish.sha |
788 |
updateMap["subOrders.$.closed"] = True
|
|
|
789 |
if status == Store.ORDER_DELIVERED:
|
|
|
790 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
791 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_APPROVED
|
|
|
792 |
elif status == Store.ORDER_CANCELLED:
|
|
|
793 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
794 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_CANCELLED
|
|
|
795 |
else:
|
| 15791 |
manish.sha |
796 |
closed = False
|
| 16155 |
manish.sha |
797 |
print 'Order not Closed'
|
| 16161 |
manish.sha |
798 |
|
| 16158 |
manish.sha |
799 |
subbulk.find(findMap).update({'$set' : updateMap})
|
|
|
800 |
subresult = subbulk.execute()
|
|
|
801 |
tprint(subresult)
|
| 16164 |
manish.sha |
802 |
count = count +1
|
| 16156 |
manish.sha |
803 |
bulk.find({'orderId': order['orderId']}).update({'$set':{'closed': closed,"parseError":False}})
|
|
|
804 |
result = bulk.execute()
|
|
|
805 |
tprint(result)
|
| 16143 |
manish.sha |
806 |
|
|
|
807 |
else:
|
| 16788 |
manish.sha |
808 |
subOrdersList = []
|
|
|
809 |
try:
|
|
|
810 |
subOrdersList = self.parseMultiSubOrders(soup, order['orderTrackingUrl'].split('email_id=')[1])
|
|
|
811 |
except:
|
|
|
812 |
print 'Unable to parse', order['orderId'], order['orderTrackingUrl']
|
|
|
813 |
continue
|
| 16143 |
manish.sha |
814 |
for subOrderObj in subOrdersList:
|
| 16159 |
manish.sha |
815 |
subbulk1 = self.db.merchantOrder.initialize_ordered_bulk_op()
|
| 16143 |
manish.sha |
816 |
subOrder = self._isSubOrderActive(order, subOrderObj.merchantSubOrderId)
|
|
|
817 |
if subOrder is None:
|
|
|
818 |
self.db.merchantOrder.update({"orderId":order['orderId']},{'$push':{"subOrders":{"$each":todict([subOrderObj])}}})
|
|
|
819 |
print "Added new suborders to Order id - ", order['orderId']
|
|
|
820 |
closed = False
|
|
|
821 |
continue
|
|
|
822 |
elif subOrder['closed']:
|
|
|
823 |
continue
|
| 15791 |
manish.sha |
824 |
else:
|
| 16143 |
manish.sha |
825 |
findMap = {"orderId": order['orderId'], "subOrders.merchantSubOrderId": subOrderId}
|
|
|
826 |
updateMap = {}
|
|
|
827 |
updateMap["subOrders.$.detailedStatus"] = subOrderObj.detailedStatus
|
|
|
828 |
status = self._getStatusFromDetailedStatus(orderStatus)
|
|
|
829 |
closedStatus = status in [Store.ORDER_DELIVERED, Store.ORDER_CANCELLED]
|
|
|
830 |
if status is not None:
|
|
|
831 |
updateMap["subOrders.$.status"] = status
|
|
|
832 |
if closedStatus:
|
|
|
833 |
#if status is closed then change the paybackStatus accordingly
|
|
|
834 |
updateMap["subOrders.$.closed"] = True
|
|
|
835 |
if status == Store.ORDER_DELIVERED:
|
|
|
836 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
837 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_APPROVED
|
|
|
838 |
elif status == Store.ORDER_CANCELLED:
|
|
|
839 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
840 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_CANCELLED
|
|
|
841 |
else:
|
|
|
842 |
closed = False
|
| 16159 |
manish.sha |
843 |
subbulk1.find(findMap).update({'$set' : updateMap})
|
|
|
844 |
subresult1 = subbulk1.execute()
|
|
|
845 |
tprint(subresult1)
|
| 16156 |
manish.sha |
846 |
bulk.find({'orderId': order['orderId']}).update({'$set':{'closed': closed,"parseError":False}})
|
|
|
847 |
result = bulk.execute()
|
|
|
848 |
tprint(result)
|
| 15509 |
manish.sha |
849 |
else:
|
| 16143 |
manish.sha |
850 |
print 'Soup Object not found for this Order', order['orderId'], order['orderTrackingUrl']
|
|
|
851 |
continue
|
| 15791 |
manish.sha |
852 |
|
|
|
853 |
'''
|
|
|
854 |
def getTrackingUrls(self, userId):
|
| 18086 |
manish.sha |
855 |
missingOrderUrls = ['https://smo.shopclues.com/myaccount','https://smo.shopclues.com/myorders']
|
| 15791 |
manish.sha |
856 |
return missingOrderUrls
|
| 15509 |
manish.sha |
857 |
|
| 15791 |
manish.sha |
858 |
def parseMyProfileForEmailId(self, userId, url, rawhtml):
|
|
|
859 |
profileSoup = BeautifulSoup(rawhtml)
|
|
|
860 |
if profileSoup.find('input', {'name':'user_email'}) is not None:
|
|
|
861 |
emailId = profileSoup.find('input', {'name':'user_email'})['value']
|
|
|
862 |
if emailId is not None and emailId.strip() !='':
|
|
|
863 |
mc = MemCache()
|
|
|
864 |
mc.set(str(userId), emailId, 600)
|
|
|
865 |
return 'EMAIL_SET_SUCCESS'
|
|
|
866 |
else:
|
|
|
867 |
return 'EMAIL_NOT_FOUND'
|
|
|
868 |
else:
|
|
|
869 |
return 'EMAIL_NOT_FOUND'
|
| 15509 |
manish.sha |
870 |
|
| 15791 |
manish.sha |
871 |
def parseMyOrdersForEmailId(self, userId, url, rawhtml):
|
|
|
872 |
myOrdersPageSoup = BeautifulSoup(rawhtml)
|
|
|
873 |
if myOrdersPageSoup.find('a', {'class':'detail'}) is not None:
|
|
|
874 |
emailId = myOrdersPageSoup.find('a', {'class':'detail'})['href'].split('&')[1].split('=')[1]
|
|
|
875 |
mc = MemCache()
|
|
|
876 |
mc.set(str(userId), emailId, 600)
|
|
|
877 |
return 'EMAIL_SET_SUCCESS'
|
|
|
878 |
else:
|
|
|
879 |
return 'EMAIL_NOT_FOUND'
|
|
|
880 |
'''
|
|
|
881 |
|
| 16420 |
manish.sha |
882 |
def to_py_date(java_timestamp):
|
| 16424 |
manish.sha |
883 |
date = datetime.fromtimestamp(java_timestamp)
|
| 16420 |
manish.sha |
884 |
return date
|
| 15791 |
manish.sha |
885 |
|
| 15509 |
manish.sha |
886 |
def todict(obj, classkey=None):
|
|
|
887 |
if isinstance(obj, dict):
|
|
|
888 |
data = {}
|
|
|
889 |
for (k, v) in obj.items():
|
|
|
890 |
data[k] = todict(v, classkey)
|
|
|
891 |
return data
|
|
|
892 |
elif hasattr(obj, "_ast"):
|
|
|
893 |
return todict(obj._ast())
|
|
|
894 |
elif hasattr(obj, "__iter__"):
|
|
|
895 |
return [todict(v, classkey) for v in obj]
|
|
|
896 |
elif hasattr(obj, "__dict__"):
|
|
|
897 |
data = dict([(key, todict(value, classkey))
|
|
|
898 |
for key, value in obj.__dict__.iteritems()
|
|
|
899 |
if not callable(value) and not key.startswith('_')])
|
|
|
900 |
if classkey is not None and hasattr(obj, "__class__"):
|
|
|
901 |
data[classkey] = obj.__class__.__name__
|
|
|
902 |
return data
|
|
|
903 |
else:
|
| 16226 |
manish.sha |
904 |
return obj
|
|
|
905 |
|
|
|
906 |
def login(url):
|
|
|
907 |
br = getBrowserObject()
|
| 16787 |
manish.sha |
908 |
br.set_proxies({"http": PROXY_MESH_GENERAL})
|
| 16226 |
manish.sha |
909 |
br.open(url)
|
|
|
910 |
response = br.open(url)
|
|
|
911 |
ungzipResponseBr(response, br)
|
|
|
912 |
#html = response.read()
|
|
|
913 |
#print html
|
| 20002 |
kshitij.so |
914 |
formcount = 0
|
|
|
915 |
for frm in br.forms():
|
|
|
916 |
if str(frm.attrs["id"])=="login":
|
|
|
917 |
break
|
|
|
918 |
formcount=formcount+1
|
|
|
919 |
br.select_form(nr=formcount)
|
| 16226 |
manish.sha |
920 |
br.form['user'] = "imanthetester@gmail.com"
|
|
|
921 |
br.form['password'] = "$Dl8uk"
|
|
|
922 |
response = br.submit()
|
|
|
923 |
print "********************"
|
|
|
924 |
print "Attempting to Login"
|
|
|
925 |
print "********************"
|
|
|
926 |
#ungzipResponse(response, br)
|
|
|
927 |
return br
|
| 15791 |
manish.sha |
928 |
|
| 16226 |
manish.sha |
929 |
def ungzipResponseBr(r,b):
|
|
|
930 |
headers = r.info()
|
|
|
931 |
if headers['Content-Encoding']=='gzip':
|
|
|
932 |
import gzip
|
|
|
933 |
print "********************"
|
|
|
934 |
print "Deflating gzip response"
|
|
|
935 |
print "********************"
|
|
|
936 |
gz = gzip.GzipFile(fileobj=r, mode='rb')
|
|
|
937 |
html = gz.read()
|
|
|
938 |
gz.close()
|
|
|
939 |
headers["Content-type"] = "text/html; charset=utf-8"
|
|
|
940 |
r.set_data( html )
|
|
|
941 |
b.set_response(r)
|
|
|
942 |
|
| 15509 |
manish.sha |
943 |
|