| Line 5... |
Line 5... |
| 5 |
'''
|
5 |
'''
|
| 6 |
from bs4 import BeautifulSoup
|
6 |
from bs4 import BeautifulSoup
|
| 7 |
from bson.binary import Binary
|
7 |
from bson.binary import Binary
|
| 8 |
from datetime import datetime, date, timedelta
|
8 |
from datetime import datetime, date, timedelta
|
| 9 |
from dtr import main
|
9 |
from dtr import main
|
| 10 |
from dtr.dao import AffiliateInfo, Order, SubOrder
|
10 |
from dtr.dao import AffiliateInfo, Order, SubOrder, ShopCluesAffiliateInfo
|
| 11 |
from dtr.main import getBrowserObject, ScrapeException, getStore, ParseException, \
|
11 |
from dtr.main import getBrowserObject, ScrapeException, getStore, ParseException, \
|
| 12 |
Store as MStore, ungzipResponse, tprint
|
12 |
Store as MStore, ungzipResponse, tprint
|
| 13 |
from dtr.storage import Mongo
|
13 |
from dtr.storage import Mongo
|
| 14 |
from dtr.storage.Mongo import getImgSrc
|
14 |
from dtr.storage.Mongo import getImgSrc
|
| 15 |
from dtr.utils.utils import fetchResponseUsingProxy
|
15 |
from dtr.utils.utils import fetchResponseUsingProxy
|
| Line 19... |
Line 19... |
| 19 |
import pymongo
|
19 |
import pymongo
|
| 20 |
import re
|
20 |
import re
|
| 21 |
import time
|
21 |
import time
|
| 22 |
import traceback
|
22 |
import traceback
|
| 23 |
import urllib
|
23 |
import urllib
|
| - |
|
24 |
import urllib2
|
| 24 |
from urlparse import urlparse, parse_qs
|
25 |
from urlparse import urlparse, parse_qs
|
| - |
|
26 |
import xml.etree.ElementTree as ET
|
| - |
|
27 |
from dtr.storage import MemCache
|
| 25 |
|
28 |
|
| 26 |
USERNAME='profittill2@gmail.com'
|
29 |
USERNAME='profittill2@gmail.com'
|
| 27 |
PASSWORD='spice@2020'
|
30 |
PASSWORD='spice@2020'
|
| 28 |
AFFILIATE_URL='http://affiliate.snapdeal.com'
|
- |
|
| 29 |
POST_URL='https://api-p03.hasoffers.com/v3/Affiliate_Report.json'
|
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"
|
| 30 |
ORDER_TRACK_URL='http://www.shopclues.com/index.php?dispatch=order_lookup.details'
|
32 |
ORDER_TRACK_URL='http://www.shopclues.com/index.php?dispatch=order_lookup.details'
|
| 31 |
CONFIG_URL='http://affiliate.snapdeal.com/publisher/js/config.php'
|
33 |
ORDER_TRACK_URL_DB='https://sm.shopclues.com/trackOrder?'
|
| 32 |
BASE_URL= 'http://www.shopclues.com'
|
34 |
BASE_URL= 'http://www.shopclues.com'
|
| 33 |
BASE_MURL= 'http://m.shopclues.com'
|
35 |
BASE_MURL= 'http://m.shopclues.com'
|
| 34 |
|
36 |
|
| 35 |
class Store(MStore):
|
37 |
class Store(MStore):
|
| 36 |
|
38 |
|
| Line 44... |
Line 46... |
| 44 |
MStore.ORDER_DELIVERED : ['delivered', 'complete'],
|
46 |
MStore.ORDER_DELIVERED : ['delivered', 'complete'],
|
| 45 |
MStore.ORDER_SHIPPED : ['in transit', 'dispatched','shipped','order handed to courier'],
|
47 |
MStore.ORDER_SHIPPED : ['in transit', 'dispatched','shipped','order handed to courier'],
|
| 46 |
MStore.ORDER_CANCELLED : ['payment failed', 'canceled', 'payment declined', 'order on hold - cancellation requested by customer', 'courier returned']
|
48 |
MStore.ORDER_CANCELLED : ['payment failed', 'canceled', 'payment declined', 'order on hold - cancellation requested by customer', 'courier returned']
|
| 47 |
}
|
49 |
}
|
| 48 |
OrderStatusConfirmationMap= {
|
50 |
OrderStatusConfirmationMap= {
|
| 49 |
"Payment Successful" : "P",
|
51 |
"P" : "Payment Successful",
|
| 50 |
"Order Declined" : "D",
|
52 |
"D" : "Order Declined",
|
| 51 |
"New Order - COD confirmation Pending" : "O"
|
53 |
"O" : "New Order - COD confirmation Pending"
|
| 52 |
}
|
54 |
}
|
| 53 |
|
55 |
|
| 54 |
CONF_CB_AMOUNT = MStore.CONF_CB_DISCOUNTED_PRICE
|
56 |
CONF_CB_AMOUNT = MStore.CONF_CB_DISCOUNTED_PRICE
|
| 55 |
'''
|
- |
|
| 56 |
def scrapeAffiliate(self, startDate=None, endDate=None):
|
- |
|
| 57 |
br = getBrowserObject()
|
- |
|
| 58 |
br.open(AFFILIATE_URL)
|
- |
|
| 59 |
br.select_form(nr=0)
|
- |
|
| 60 |
br.form['data[User][password]'] = PASSWORD
|
- |
|
| 61 |
br.form['data[User][email]'] = USERNAME
|
- |
|
| 62 |
br.submit()
|
- |
|
| 63 |
response = br.open(CONFIG_URL)
|
- |
|
| 64 |
|
- |
|
| 65 |
token = re.findall('"session_token":"(.*?)"', ungzipResponse(response), re.IGNORECASE)[0]
|
- |
|
| 66 |
print token
|
- |
|
| 67 |
allOffers = self._getAllOffers(br, token)
|
- |
|
| 68 |
self._saveToAffiliate(allOffers)
|
- |
|
| 69 |
'''
|
- |
|
| 70 |
|
57 |
|
| - |
|
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 |
|
| - |
|
72 |
def scrapeAffiliate(self, startDate=datetime.datetime.today() - datetime.timedelta(days=10), endDate=datetime.datetime.today()):
|
| - |
|
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 |
|
| 71 |
def _setLastSaleDate(self, saleDate):
|
81 |
def _setLastSaleDate(self, saleDate):
|
| 72 |
self.db.lastSaleDtate.update({'storeId':self.store_id}, {'$set':{'saleDate':saleDate}})
|
82 |
self.db.lastSaleDtate.update({'storeId':self.store_id}, {'$set':{'saleDate':saleDate}})
|
| 73 |
|
83 |
|
| 74 |
def getName(self):
|
84 |
def getName(self):
|
| 75 |
return "shopclues"
|
85 |
return "shopclues"
|
| Line 84... |
Line 94... |
| 84 |
if detailedStatus.lower() in value:
|
94 |
if detailedStatus.lower() in value:
|
| 85 |
return key
|
95 |
return key
|
| 86 |
print "Detailed Status need to be mapped", detailedStatus, self.store_id
|
96 |
print "Detailed Status need to be mapped", detailedStatus, self.store_id
|
| 87 |
return None
|
97 |
return None
|
| 88 |
|
98 |
|
| 89 |
def _getSingleSubOrderMap(self, orderId, orderStatus, statusTime, soup, subTagId):
|
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()
|
| 90 |
productDetailsMap = {}
|
102 |
productDetailsMap = {}
|
| 91 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
103 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| 92 |
orderTable.pop(0)
|
104 |
firstRow = orderTable.pop(0)
|
| - |
|
105 |
totalColumns = len(firstRow.find_all('td'))
|
| 93 |
productDetailsSubMap = {}
|
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
|
| 94 |
for orderTr in orderTable:
|
125 |
for orderTr in orderTable:
|
| - |
|
126 |
productDetailsSubMap = None
|
| - |
|
127 |
productDetailsSubMap = {}
|
| 95 |
cols = orderTr.find_all('td')
|
128 |
cols = orderTr.find_all('td')
|
| 96 |
product_details = cols[0].find_all('a')
|
129 |
product_details = cols[0].find_all('a')
|
| 97 |
#print product_details
|
130 |
#print product_details
|
| 98 |
productUrl = product_details[0].get('href')
|
131 |
productUrl = product_details[0].get('href')
|
| 99 |
productName = product_details[0].contents[0].strip()
|
132 |
productName = product_details[0].contents[0].strip()
|
| 100 |
quantity = int(cols[1].text.strip())
|
133 |
quantity = int(cols[1].text.strip())
|
| 101 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
134 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
| - |
|
135 |
discount = 0
|
| - |
|
136 |
subtotal = 0
|
| - |
|
137 |
if totalColumns == 5:
|
| - |
|
138 |
if cols[3].text.strip()!='-' or 'Rs.' in cols[3].text.strip():
|
| 102 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
139 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
| - |
|
140 |
else:
|
| - |
|
141 |
discount = 0
|
| 103 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
142 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
| - |
|
143 |
else:
|
| - |
|
144 |
subtotal = long(cols[3].text.strip().replace("Rs.",""))
|
| 104 |
productDetailsSubMap['productUrl']=BASE_MURL+productUrl
|
145 |
productDetailsSubMap['productUrl']=BASE_MURL+productUrl
|
| 105 |
productDetailsSubMap['productName']=productName
|
146 |
productDetailsSubMap['productName']=productName
|
| 106 |
productDetailsSubMap['subOrderTrackingUrl']=ORDER_TRACK_URL+'&order_id=' +str(orderId)+'&email_id='+ subTagId.split('$')[1]
|
147 |
productDetailsSubMap['subOrderTrackingUrl']=ORDER_TRACK_URL_DB+'order_id=' +str(orderId)+'&email_id='+ orderObj['0']['email']
|
| 107 |
productDetailsSubMap['sellingPrice']=sellingPrice
|
148 |
productDetailsSubMap['sellingPrice']=sellingPrice
|
| 108 |
productDetailsSubMap['quantity']=quantity
|
149 |
productDetailsSubMap['quantity']=quantity
|
| 109 |
productDetailsSubMap['discount']=discount
|
150 |
productDetailsSubMap['discount']=discount
|
| 110 |
productDetailsSubMap['subtotal']=subtotal
|
151 |
productDetailsSubMap['subtotal']=subtotal
|
| 111 |
productDetailsSubMap['parentOrderId']=orderId
|
152 |
jsonSubOrderDetails = jsonSubOrdersMap.get(str(orderId)+'-'+str(count))
|
| 112 |
br = getBrowserObject()
|
- |
|
| 113 |
productPage = br.open(BASE_MURL+productUrl)
|
- |
|
| 114 |
productPageHeaders = str(productPage.info()).split('\n')
|
- |
|
| 115 |
productPage = ungzipResponse(productPage)
|
- |
|
| 116 |
jsonProductResponse = None
|
- |
|
| 117 |
for header in productPageHeaders:
|
- |
|
| 118 |
header = header.split(':')
|
- |
|
| 119 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
- |
|
| 120 |
jsonProductResponse = json.loads(productPage)
|
- |
|
| 121 |
productPageSoup= None
|
- |
|
| 122 |
if jsonProductResponse is not None:
|
- |
|
| 123 |
productPageSoup = BeautifulSoup(jsonProductResponse['text'])
|
- |
|
| 124 |
else:
|
- |
|
| 125 |
productPageSoup = BeautifulSoup(productPage)
|
- |
|
| 126 |
productCodeArray = str(productPageSoup.find("form", {'class':'buy-form'}).findAll('input', recursive=False)[0]).split('"')
|
- |
|
| 127 |
lengthProductCodeArr= len(productCodeArray)
|
- |
|
| 128 |
productCode = productCodeArray[lengthProductCodeArr-2]
|
153 |
productCode = jsonSubOrderDetails['product_code']
|
| 129 |
allproductImageTags = productPageSoup.findAll(attrs={'class' : 'pd-image'})
|
- |
|
| 130 |
productImgUrl = ''
|
- |
|
| 131 |
if allproductImageTags is not None and len(allproductImageTags)>0:
|
154 |
productImgUrl = jsonSubOrderDetails['images']['image_path'][0]
|
| 132 |
productImgUrl= allproductImageTags[0].get('style').split("background:url('")[1].split("')no-repeat center")[0].strip()
|
- |
|
| 133 |
productDetailsSubMap['productCode']=productCode
|
155 |
productDetailsSubMap['productCode']=productCode
|
| 134 |
productDetailsSubMap['imgUrl']=productImgUrl
|
156 |
productDetailsSubMap['imgUrl']=productImgUrl
|
| 135 |
|
157 |
|
| 136 |
productDetailsSubMap['subOrderStatus']=orderStatus
|
158 |
productDetailsSubMap['subOrderStatus']=orderStatus
|
| 137 |
productDetailsSubMap['subOrderStatusTime']=statusTime
|
159 |
productDetailsSubMap['subOrderStatusTime']=statusTime
|
| 138 |
productDetailsMap[orderId]=productDetailsSubMap
|
160 |
productDetailsMap[str(orderId)+'-'+str(count)]=productDetailsSubMap
|
| - |
|
161 |
count = count +1
|
| 139 |
return productDetailsMap
|
162 |
return productDetailsMap
|
| 140 |
|
163 |
|
| 141 |
def _getMultiSubOrdersMap(self, orderId, soup):
|
164 |
def _getMultiSubOrdersMap(self, orderId, soup, orderObj):
|
| 142 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
165 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| 143 |
orderTable.pop(0)
|
166 |
#firstRow = orderTable.pop(0)
|
| - |
|
167 |
#totalColumns = len(firstRow.find_all('td'))
|
| 144 |
productDetailsMap = {}
|
168 |
productDetailsMap = {}
|
| - |
|
169 |
'''
|
| - |
|
170 |
jsonSubOrdersMap = {}
|
| - |
|
171 |
for val in orderObj['0']['items'].values():
|
| - |
|
172 |
jsonSubOrdersMap[val['order_id']] = val
|
| - |
|
173 |
'''
|
| - |
|
174 |
existingOrders = []
|
| 145 |
for orderTr in orderTable:
|
175 |
for orderTr in orderTable:
|
| 146 |
productDetailsSubMap = {}
|
176 |
subOrderDetailsMap = {}
|
| - |
|
177 |
|
| 147 |
cols = orderTr.find_all('td')
|
178 |
cols = orderTr.find_all('td')
|
| 148 |
product_details = cols[0].find_all('a')
|
179 |
product_details = cols[0].find_all('a')
|
| 149 |
#print product_details
|
180 |
#print product_details
|
| 150 |
subOrderId= product_details[1].contents[0].strip()
|
181 |
subOrderId= product_details[1].contents[0].strip()
|
| - |
|
182 |
if subOrderId in existingOrders:
|
| - |
|
183 |
continue
|
| - |
|
184 |
else:
|
| - |
|
185 |
existingOrders.append(subOrderId)
|
| 151 |
productUrl = product_details[0].get('href')
|
186 |
#productUrl = product_details[0].get('href')
|
| 152 |
productName = product_details[0].contents[0].strip()
|
187 |
#productName = product_details[0].contents[0].strip()
|
| 153 |
subOrderTrackingUrl = product_details[1].get('href')
|
188 |
subOrderTrackingParsingUrl = product_details[1].get('href')
|
| - |
|
189 |
#subOrderTrackingUrl = subOrderTrackingParsingUrl.split('order_lookup.details&')[1]
|
| - |
|
190 |
'''
|
| 154 |
quantity = int(cols[1].text.strip())
|
191 |
quantity = int(cols[1].text.strip())
|
| 155 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
192 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
| - |
|
193 |
discount = 0
|
| - |
|
194 |
subtotal = 0
|
| - |
|
195 |
if totalColumns == 5:
|
| - |
|
196 |
if cols[3].text.strip()!='-' or 'Rs.' in cols[3].text.strip():
|
| 156 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
197 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
| - |
|
198 |
else:
|
| - |
|
199 |
discount = 0
|
| 157 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
200 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
| - |
|
201 |
else:
|
| - |
|
202 |
subtotal = long(cols[3].text.strip().replace("Rs.",""))
|
| 158 |
productDetailsSubMap['productUrl']=BASE_MURL+productUrl
|
203 |
productDetailsSubMap['productUrl']=BASE_MURL+productUrl
|
| 159 |
productDetailsSubMap['productName']=productName
|
204 |
productDetailsSubMap['productName']=productName
|
| 160 |
productDetailsSubMap['subOrderTrackingUrl']=BASE_URL+subOrderTrackingUrl
|
205 |
productDetailsSubMap['subOrderTrackingUrl']=ORDER_TRACK_URL_DB+subOrderTrackingUrl
|
| 161 |
productDetailsSubMap['sellingPrice']=sellingPrice
|
206 |
productDetailsSubMap['sellingPrice']=sellingPrice
|
| 162 |
productDetailsSubMap['quantity']=quantity
|
207 |
productDetailsSubMap['quantity']=quantity
|
| 163 |
productDetailsSubMap['discount']=discount
|
208 |
productDetailsSubMap['discount']=discount
|
| 164 |
productDetailsSubMap['subtotal']=subtotal
|
209 |
productDetailsSubMap['subtotal']=subtotal
|
| 165 |
br = getBrowserObject()
|
- |
|
| 166 |
productPage = br.open(BASE_MURL+productUrl)
|
- |
|
| 167 |
productPageHeaders = str(productPage.info()).split('\n')
|
210 |
jsonSubOrderDetails = jsonSubOrdersMap.get(subOrderId)
|
| 168 |
productPage = ungzipResponse(productPage)
|
- |
|
| 169 |
jsonProductResponse = None
|
- |
|
| 170 |
for header in productPageHeaders:
|
- |
|
| 171 |
header = header.split(':')
|
- |
|
| 172 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
- |
|
| 173 |
jsonProductResponse = json.loads(productPage)
|
- |
|
| 174 |
productPageSoup= None
|
- |
|
| 175 |
if jsonProductResponse is not None:
|
- |
|
| 176 |
productPageSoup = BeautifulSoup(jsonProductResponse['text'])
|
- |
|
| 177 |
else:
|
- |
|
| 178 |
productPageSoup = BeautifulSoup(productPage)
|
- |
|
| 179 |
productCodeArray = str(productPageSoup.find("form", {'class':'buy-form'}).findAll('input', recursive=False)[0]).split('"')
|
- |
|
| 180 |
lengthProductCodeArr= len(productCodeArray)
|
- |
|
| 181 |
productCode = productCodeArray[lengthProductCodeArr-2]
|
211 |
productCode = jsonSubOrderDetails['product_code']
|
| 182 |
allproductImageTags = productPageSoup.findAll(attrs={'class' : 'pd-image'})
|
- |
|
| 183 |
productImgUrl = ''
|
- |
|
| 184 |
if allproductImageTags is not None and len(allproductImageTags)>0:
|
212 |
productImgUrl = jsonSubOrderDetails['images']['image_path'][0]
|
| 185 |
productImgUrl= allproductImageTags[0].get('style').split("background:url('")[1].split("')no-repeat center")[0].strip()
|
- |
|
| 186 |
productDetailsSubMap['productCode']=productCode
|
213 |
productDetailsSubMap['productCode']=productCode
|
| 187 |
productDetailsSubMap['imgUrl']=productImgUrl
|
214 |
productDetailsSubMap['imgUrl']=productImgUrl
|
| - |
|
215 |
'''
|
| 188 |
br1 = getBrowserObject()
|
216 |
br1 = getBrowserObject()
|
| 189 |
orderTrackingPage = br1.open(BASE_URL+subOrderTrackingUrl)
|
217 |
orderTrackingPage = br1.open(BASE_URL+'&'+subOrderTrackingParsingUrl)
|
| 190 |
headers = str(orderTrackingPage.info()).split('\n')
|
218 |
headers = str(orderTrackingPage.info()).split('\n')
|
| 191 |
orderTrackingPage= ungzipResponse(orderTrackingPage)
|
219 |
orderTrackingPage= ungzipResponse(orderTrackingPage)
|
| 192 |
jsonResponse = None
|
220 |
jsonResponse = None
|
| 193 |
for header in headers:
|
221 |
for header in headers:
|
| 194 |
header = header.split(':')
|
222 |
header = header.split(':')
|
| Line 198... |
Line 226... |
| 198 |
orderTrackingPageSoup = None
|
226 |
orderTrackingPageSoup = None
|
| 199 |
if jsonResponse is not None:
|
227 |
if jsonResponse is not None:
|
| 200 |
orderTrackingPageSoup = BeautifulSoup(str(jsonResponse['text']))
|
228 |
orderTrackingPageSoup = BeautifulSoup(str(jsonResponse['text']))
|
| 201 |
else:
|
229 |
else:
|
| 202 |
orderTrackingPageSoup = BeautifulSoup(orderTrackingPage)
|
230 |
orderTrackingPageSoup = BeautifulSoup(orderTrackingPage)
|
| - |
|
231 |
'''
|
| 203 |
subOrderStatusList = orderTrackingPageSoup.findAll(attrs={'class' : 'price ord_status'})
|
232 |
subOrderStatusList = orderTrackingPageSoup.findAll(attrs={'class' : 'price ord_status'})
|
| 204 |
subOrderStatus = subOrderStatusList[0].contents[0].strip()
|
233 |
subOrderStatus = subOrderStatusList[0].contents[0].strip()
|
| 205 |
subOrderStatusTime= orderTrackingPageSoup.findAll(attrs={'class' : 'sts no_mobile'})[1].contents[2].strip()
|
234 |
subOrderStatusTime= orderTrackingPageSoup.findAll(attrs={'class' : 'sts no_mobile'})[1].contents[2].strip()
|
| 206 |
productDetailsSubMap['subOrderStatus'] = subOrderStatus
|
235 |
productDetailsSubMap['subOrderStatus'] = subOrderStatus
|
| 207 |
productDetailsSubMap['subOrderStatusTime'] = subOrderStatusTime
|
236 |
productDetailsSubMap['subOrderStatusTime'] = subOrderStatusTime
|
| 208 |
productDetailsSubMap['parentOrderId']=orderId
|
237 |
productDetailsSubMap['parentOrderId']=orderId
|
| - |
|
238 |
'''
|
| - |
|
239 |
|
| - |
|
240 |
subOrderDetailsMap = self._getSingleSubOrderMap(subOrderId, orderTrackingPageSoup, orderObj)
|
| 209 |
|
241 |
|
| 210 |
productDetailsMap[subOrderId]=productDetailsSubMap
|
242 |
productDetailsMap = dict(productDetailsMap.items()+subOrderDetailsMap.items())
|
| 211 |
|
243 |
|
| 212 |
return productDetailsMap
|
244 |
return productDetailsMap
|
| 213 |
|
245 |
|
| 214 |
def updateCashbackInSubOrders(self, subOrders):
|
246 |
def updateCashbackInSubOrders(self, subOrders):
|
| 215 |
for subOrder in subOrders:
|
247 |
for subOrder in subOrders:
|
| Line 224... |
Line 256... |
| 224 |
subOrder.cashBackStatus = cashbackStatus
|
256 |
subOrder.cashBackStatus = cashbackStatus
|
| 225 |
subOrder.cashBackAmount = cashbackAmount
|
257 |
subOrder.cashBackAmount = cashbackAmount
|
| 226 |
subOrder.cashBackPercentage = percentage
|
258 |
subOrder.cashBackPercentage = percentage
|
| 227 |
return subOrders
|
259 |
return subOrders
|
| 228 |
|
260 |
|
| 229 |
def _parseOrders(self, orderId, subTagId, userId, page, orderSuccessUrl):
|
261 |
def _parseOrders(self, orderId, subTagId, userId, page, orderSuccessUrl, orderObj):
|
| 230 |
soup = BeautifulSoup(page)
|
262 |
soup = BeautifulSoup(page)
|
| 231 |
productDetailsMap = {}
|
263 |
productDetailsMap = {}
|
| 232 |
orderStatusList = soup.findAll(attrs={'class' : 'price ord_status'})
|
- |
|
| 233 |
paymentFields = soup.findAll(attrs={'class' : 'box_paymentcalculations_row'})
|
264 |
paymentFields = soup.findAll(attrs={'class' : 'box_paymentcalculations_row'})
|
| 234 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
265 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
| 235 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace(" ","")
|
266 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace(" ","")
|
| 236 |
ordersubtotal=0
|
267 |
ordersubtotal=0
|
| 237 |
ordercluebucks=0
|
268 |
ordercluebucks=0
|
| Line 250... |
Line 281... |
| 250 |
print ordershippingcost
|
281 |
print ordershippingcost
|
| 251 |
if 'Clue' in value.text.strip():
|
282 |
if 'Clue' in value.text.strip():
|
| 252 |
ordercluebucks = long(val.contents[3].text.strip().replace("Rs.",""))
|
283 |
ordercluebucks = long(val.contents[3].text.strip().replace("Rs.",""))
|
| 253 |
print ordercluebucks
|
284 |
print ordercluebucks
|
| 254 |
if 'Total' in value.text.strip():
|
285 |
if 'Total' in value.text.strip():
|
| 255 |
ordertotal = long(val.contents[3].text.strip().replace("Rs.",""))
|
286 |
ordertotal = val.contents[3].text.strip().replace("Rs.","")
|
| - |
|
287 |
ordertotal = ordertotal.replace(',','')
|
| 256 |
print ordertotal
|
288 |
print ordertotal
|
| 257 |
|
289 |
|
| 258 |
if orderStatusList is not None and len(orderStatusList)>0:
|
290 |
if orderObj['0']['is_parent_order'] == 'N':
|
| 259 |
orderStatus = orderStatusList[0].contents[0].strip()
|
- |
|
| 260 |
statusTime= soup.findAll(attrs={'class' : 'sts no_mobile'})[1].contents[2].strip()
|
- |
|
| 261 |
productDetailsMap = self._getSingleSubOrderMap(orderId, orderStatus, statusTime, soup, subTagId)
|
291 |
productDetailsMap = self._getSingleSubOrderMap(orderId, soup, orderObj)
|
| 262 |
else:
|
292 |
else:
|
| 263 |
productDetailsMap = self._getMultiSubOrdersMap(orderId, soup)
|
293 |
productDetailsMap = self._getMultiSubOrdersMap(orderId, soup, orderObj)
|
| 264 |
|
294 |
|
| 265 |
merchantOrder = Order(orderId, userId, subTagId.split('$')[0], self.store_id, orderSuccessUrl)
|
295 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
|
| 266 |
merchantOrder.placedOn = placedOn
|
296 |
merchantOrder.placedOn = placedOn
|
| 267 |
merchantOrder.merchantOrderId = orderId
|
297 |
merchantOrder.merchantOrderId = orderObj['0']['order_id']
|
| 268 |
merchantOrder.paidAmount = ordertotal
|
298 |
merchantOrder.paidAmount = ordertotal
|
| 269 |
totalOrdersAmount = 0
|
299 |
totalOrdersAmount = 0
|
| 270 |
totalDiscount = 0
|
300 |
totalDiscount = 0
|
| 271 |
subOrders= []
|
301 |
subOrders= []
|
| 272 |
for key in productDetailsMap:
|
302 |
for key in productDetailsMap:
|
| Line 280... |
Line 310... |
| 280 |
subOrder.offerDiscount = subOrderDetail['discount'] * subOrderDetail['quantity']
|
310 |
subOrder.offerDiscount = subOrderDetail['discount'] * subOrderDetail['quantity']
|
| 281 |
subOrder.unitPrice = subOrderDetail['sellingPrice']
|
311 |
subOrder.unitPrice = subOrderDetail['sellingPrice']
|
| 282 |
subOrder.productCode = subOrderDetail['productCode']
|
312 |
subOrder.productCode = subOrderDetail['productCode']
|
| 283 |
subOrder.amountPaid = subOrderDetail['subtotal']
|
313 |
subOrder.amountPaid = subOrderDetail['subtotal']
|
| 284 |
subOrder.quantity = subOrderDetail['quantity']
|
314 |
subOrder.quantity = subOrderDetail['quantity']
|
| - |
|
315 |
subOrder.tracingkUrl = subOrderDetail['subOrderTrackingUrl']
|
| 285 |
subOrders.append(subOrder)
|
316 |
subOrders.append(subOrder)
|
| 286 |
print totalOrdersAmount, totalDiscount
|
317 |
print totalOrdersAmount, totalDiscount
|
| 287 |
merchantOrder.totalAmount = totalOrdersAmount
|
318 |
merchantOrder.totalAmount = totalOrdersAmount
|
| 288 |
merchantOrder.discountApplied = totalDiscount
|
319 |
merchantOrder.discountApplied = totalDiscount
|
| 289 |
merchantOrder.deliveryCharges = ordershippingcost
|
320 |
merchantOrder.deliveryCharges = ordershippingcost
|
| 290 |
merchantOrder.subOrders = self.updateCashbackInSubOrders(subOrders)
|
321 |
merchantOrder.subOrders = self.updateCashbackInSubOrders(subOrders)
|
| 291 |
|
322 |
|
| 292 |
return merchantOrder
|
323 |
return merchantOrder
|
| 293 |
|
324 |
|
| 294 |
def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
|
325 |
def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
|
| 295 |
#print merchantOrder
|
- |
|
| 296 |
resp = {}
|
326 |
resp = {}
|
| 297 |
try:
|
327 |
try:
|
| - |
|
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 |
|
| 298 |
br = getBrowserObject()
|
339 |
br = getBrowserObject()
|
| 299 |
url = ORDER_TRACK_URL +'&order_id=' +str(orderId)+'&email_id='+ subTagId.split('$')[1]
|
340 |
url = ORDER_TRACK_URL +'&order_id=' +str(merchantOrderId)+'&email_id='+ emailId
|
| 300 |
page = br.open(url)
|
341 |
page = br.open(url)
|
| 301 |
headers = str(page.info()).split('\n')
|
342 |
headers = str(page.info()).split('\n')
|
| 302 |
page = ungzipResponse(page)
|
343 |
page = ungzipResponse(page)
|
| 303 |
jsonResponse = None
|
344 |
jsonResponse = None
|
| 304 |
for header in headers:
|
345 |
for header in headers:
|
| Line 306... |
Line 347... |
| 306 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
347 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
| 307 |
jsonResponse = json.loads(page)
|
348 |
jsonResponse = json.loads(page)
|
| 308 |
if jsonResponse is not None:
|
349 |
if jsonResponse is not None:
|
| 309 |
page = jsonResponse['text']
|
350 |
page = jsonResponse['text']
|
| 310 |
|
351 |
|
| 311 |
merchantOrder = self._parseOrders(orderId, subTagId, userId, page, orderSuccessUrl)
|
352 |
merchantOrder = self._parseOrders(orderId, subTagId, userId, page, orderSuccessUrl, orderObj)
|
| 312 |
|
353 |
|
| 313 |
merchantOrder.orderTrackingUrl = url
|
354 |
merchantOrder.orderTrackingUrl = ORDER_TRACK_URL_DB + 'order_id=' +str(orderId)+'&email_id='+ emailId
|
| 314 |
|
355 |
|
| 315 |
if self._saveToOrder(todict(merchantOrder)):
|
356 |
if self._saveToOrder(todict(merchantOrder)):
|
| 316 |
resp['result'] = 'ORDER_CREATED'
|
357 |
resp['result'] = 'ORDER_CREATED'
|
| 317 |
else:
|
358 |
else:
|
| 318 |
resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
|
359 |
resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
|
| Line 321... |
Line 362... |
| 321 |
except:
|
362 |
except:
|
| 322 |
print "Error occurred"
|
363 |
print "Error occurred"
|
| 323 |
traceback.print_exc()
|
364 |
traceback.print_exc()
|
| 324 |
resp['result'] = 'ORDER_NOT_CREATED'
|
365 |
resp['result'] = 'ORDER_NOT_CREATED'
|
| 325 |
|
366 |
|
| 326 |
def parseSingleSubOrder(self, soup, emailId, subOrderId, subOrderStatus):
|
367 |
def parseSingleSubOrder(self, soup, emailId, subOrderId):
|
| - |
|
368 |
orderStatusList = soup.findAll(attrs={'class' : 'price ord_status'})
|
| - |
|
369 |
subOrderStatus = orderStatusList[0].contents[0].strip()
|
| 327 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
370 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
| 328 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace(" ","")
|
371 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace(" ","")
|
| 329 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
372 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| 330 |
orderTable.pop(0)
|
373 |
firstRow = orderTable.pop(0)
|
| - |
|
374 |
totalColumns = len(firstRow.find_all('td'))
|
| 331 |
subOrders =[]
|
375 |
subOrders =[]
|
| - |
|
376 |
count =1
|
| 332 |
for orderTr in orderTable:
|
377 |
for orderTr in orderTable:
|
| 333 |
cols = orderTr.find_all('td')
|
378 |
cols = orderTr.find_all('td')
|
| 334 |
product_details = cols[0].find_all('a')
|
379 |
product_details = cols[0].find_all('a')
|
| 335 |
#print product_details
|
380 |
#print product_details
|
| 336 |
productUrl = product_details[0].get('href')
|
381 |
productUrl = product_details[0].get('href')
|
| 337 |
productName = product_details[0].contents[0].strip()
|
382 |
productName = product_details[0].contents[0].strip()
|
| 338 |
quantity = int(cols[1].text.strip())
|
383 |
quantity = int(cols[1].text.strip())
|
| 339 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
384 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
| - |
|
385 |
discount = 0
|
| - |
|
386 |
subtotal = 0
|
| - |
|
387 |
if totalColumns == 5:
|
| - |
|
388 |
if cols[3].text.strip()!='-' or 'Rs.' in cols[3].text.strip():
|
| 340 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
389 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
| - |
|
390 |
else:
|
| - |
|
391 |
discount = 0
|
| 341 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
392 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
| - |
|
393 |
else:
|
| - |
|
394 |
subtotal = long(cols[3].text.strip().replace("Rs.",""))
|
| 342 |
br = getBrowserObject()
|
395 |
br = getBrowserObject()
|
| 343 |
productPage = br.open(BASE_MURL+productUrl)
|
396 |
productPage = br.open(BASE_MURL+productUrl)
|
| 344 |
productPageHeaders = str(productPage.info()).split('\n')
|
397 |
productPageHeaders = str(productPage.info()).split('\n')
|
| 345 |
productPage = ungzipResponse(productPage)
|
398 |
productPage = ungzipResponse(productPage)
|
| 346 |
jsonProductResponse = None
|
399 |
jsonProductResponse = None
|
| Line 351... |
Line 404... |
| 351 |
productPageSoup= None
|
404 |
productPageSoup= None
|
| 352 |
if jsonProductResponse is not None:
|
405 |
if jsonProductResponse is not None:
|
| 353 |
productPageSoup = BeautifulSoup(jsonProductResponse['text'])
|
406 |
productPageSoup = BeautifulSoup(jsonProductResponse['text'])
|
| 354 |
else:
|
407 |
else:
|
| 355 |
productPageSoup = BeautifulSoup(productPage)
|
408 |
productPageSoup = BeautifulSoup(productPage)
|
| 356 |
productCodeArray = str(productPageSoup.find("form", {'class':'buy-form'}).findAll('input', recursive=False)[0]).split('"')
|
- |
|
| 357 |
lengthProductCodeArr= len(productCodeArray)
|
- |
|
| 358 |
productCode = productCodeArray[lengthProductCodeArr-2]
|
409 |
productCode = productPageSoup.find('input', {'type':'hidden'})['value']
|
| 359 |
allproductImageTags = productPageSoup.findAll(attrs={'class' : 'pd-image'})
|
410 |
allproductImageTags = productPageSoup.findAll(attrs={'class' : 'pd-image'})
|
| 360 |
productImgUrl = ''
|
411 |
productImgUrl = ''
|
| 361 |
if allproductImageTags is not None and len(allproductImageTags)>0:
|
412 |
if allproductImageTags is not None and len(allproductImageTags)>0:
|
| 362 |
productImgUrl= allproductImageTags[0].get('style').split("background:url('")[1].split("')no-repeat center")[0].strip()
|
413 |
productImgUrl= allproductImageTags[0].get('style').split("background:url('")[1].split("')no-repeat center")[0].strip()
|
| 363 |
|
414 |
|
| 364 |
subOrder = SubOrder(productName, productUrl, placedOn, subtotal)
|
415 |
subOrder = SubOrder(productName, productUrl, placedOn, subtotal)
|
| 365 |
subOrder.merchantSubOrderId = subOrderId
|
416 |
subOrder.merchantSubOrderId = str(subOrderId)+'-'+str(count)
|
| 366 |
subOrder.detailedStatus = subOrderStatus
|
417 |
subOrder.detailedStatus = subOrderStatus
|
| 367 |
subOrder.imgUrl = productImgUrl
|
418 |
subOrder.imgUrl = productImgUrl
|
| 368 |
subOrder.offerDiscount = discount*quantity
|
419 |
subOrder.offerDiscount = discount*quantity
|
| 369 |
subOrder.unitPrice = sellingPrice
|
420 |
subOrder.unitPrice = sellingPrice
|
| 370 |
subOrder.productCode = productCode
|
421 |
subOrder.productCode = productCode
|
| 371 |
subOrder.amountPaid = subtotal
|
422 |
subOrder.amountPaid = subtotal
|
| 372 |
subOrder.quantity = quantity
|
423 |
subOrder.quantity = quantity
|
| 373 |
|
424 |
subOrder.tracingkUrl = ORDER_TRACK_URL_DB + 'order_id=' +subOrderId+'&email_id='+ emailId
|
| 374 |
subOrders.append(subOrder)
|
425 |
subOrders.append(subOrder)
|
| - |
|
426 |
count = count +1
|
| 375 |
|
427 |
|
| 376 |
subOrders = self.updateCashbackInSubOrders(subOrders)
|
428 |
subOrders = self.updateCashbackInSubOrders(subOrders)
|
| 377 |
return subOrders[0]
|
429 |
return subOrders
|
| 378 |
|
430 |
|
| 379 |
def parseMultiSubOrders(self, soup):
|
431 |
def parseMultiSubOrders(self, soup, emailId):
|
| 380 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
432 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| - |
|
433 |
'''
|
| 381 |
orderTable.pop(0)
|
434 |
firstRow = orderTable.pop(0)
|
| - |
|
435 |
totalColumns = len(firstRow.find_all('td'))
|
| - |
|
436 |
|
| 382 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
437 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
| 383 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace(" ","")
|
438 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace(" ","")
|
| - |
|
439 |
'''
|
| 384 |
subOrders = []
|
440 |
subOrders = []
|
| - |
|
441 |
existingOrders = []
|
| 385 |
for orderTr in orderTable:
|
442 |
for orderTr in orderTable:
|
| 386 |
productDetailsSubMap = {}
|
- |
|
| 387 |
cols = orderTr.find_all('td')
|
443 |
cols = orderTr.find_all('td')
|
| 388 |
product_details = cols[0].find_all('a')
|
444 |
product_details = cols[0].find_all('a')
|
| 389 |
#print product_details
|
445 |
#print product_details
|
| 390 |
subOrderId= product_details[1].contents[0].strip()
|
446 |
subOrderId= product_details[1].contents[0].strip()
|
| - |
|
447 |
if subOrderId in existingOrders:
|
| - |
|
448 |
continue
|
| - |
|
449 |
else:
|
| - |
|
450 |
existingOrders.append(subOrderId)
|
| - |
|
451 |
'''
|
| 391 |
productUrl = product_details[0].get('href')
|
452 |
productUrl = product_details[0].get('href')
|
| 392 |
productName = product_details[0].contents[0].strip()
|
453 |
productName = product_details[0].contents[0].strip()
|
| - |
|
454 |
'''
|
| 393 |
subOrderTrackingUrl = product_details[1].get('href')
|
455 |
subOrderTrackingParsingUrl = product_details[1].get('href')
|
| - |
|
456 |
#subOrderTrackingUrl = subOrderTrackingParsingUrl.split('order_lookup.details&')[1]
|
| - |
|
457 |
'''
|
| 394 |
quantity = int(cols[1].text.strip())
|
458 |
quantity = int(cols[1].text.strip())
|
| 395 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
459 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
| - |
|
460 |
discount = 0
|
| - |
|
461 |
subtotal = 0
|
| - |
|
462 |
if totalColumns == 5:
|
| - |
|
463 |
if cols[3].text.strip()!='-' or 'Rs.' in cols[3].text.strip():
|
| 396 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
464 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
| - |
|
465 |
else:
|
| - |
|
466 |
discount = 0
|
| 397 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
467 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
| - |
|
468 |
else:
|
| - |
|
469 |
subtotal = long(cols[3].text.strip().replace("Rs.",""))
|
| - |
|
470 |
|
| 398 |
br = getBrowserObject()
|
471 |
br = getBrowserObject()
|
| 399 |
productPage = br.open(BASE_MURL+productUrl)
|
472 |
productPage = br.open(BASE_MURL+productUrl)
|
| 400 |
productPageHeaders = str(productPage.info()).split('\n')
|
473 |
productPageHeaders = str(productPage.info()).split('\n')
|
| 401 |
productPage = ungzipResponse(productPage)
|
474 |
productPage = ungzipResponse(productPage)
|
| 402 |
jsonProductResponse = None
|
475 |
jsonProductResponse = None
|
| Line 407... |
Line 480... |
| 407 |
productPageSoup= None
|
480 |
productPageSoup= None
|
| 408 |
if jsonProductResponse is not None:
|
481 |
if jsonProductResponse is not None:
|
| 409 |
productPageSoup = BeautifulSoup(jsonProductResponse['text'])
|
482 |
productPageSoup = BeautifulSoup(jsonProductResponse['text'])
|
| 410 |
else:
|
483 |
else:
|
| 411 |
productPageSoup = BeautifulSoup(productPage)
|
484 |
productPageSoup = BeautifulSoup(productPage)
|
| 412 |
productCodeArray = str(productPageSoup.find("form", {'class':'buy-form'}).findAll('input', recursive=False)[0]).split('"')
|
- |
|
| 413 |
lengthProductCodeArr= len(productCodeArray)
|
- |
|
| 414 |
productCode = productCodeArray[lengthProductCodeArr-2]
|
485 |
productCode = productPageSoup.find('input', {'type':'hidden'})['value']
|
| 415 |
allproductImageTags = productPageSoup.findAll(attrs={'class' : 'pd-image'})
|
486 |
allproductImageTags = productPageSoup.findAll(attrs={'class' : 'pd-image'})
|
| 416 |
productImgUrl = ''
|
487 |
productImgUrl = ''
|
| 417 |
if allproductImageTags is not None and len(allproductImageTags)>0:
|
488 |
if allproductImageTags is not None and len(allproductImageTags)>0:
|
| 418 |
productImgUrl= allproductImageTags[0].get('style').split("background:url('")[1].split("')no-repeat center")[0].strip()
|
489 |
productImgUrl= allproductImageTags[0].get('style').split("background:url('")[1].split("')no-repeat center")[0].strip()
|
| 419 |
productDetailsSubMap['productCode']=productCode
|
490 |
productDetailsSubMap['productCode']=productCode
|
| 420 |
productDetailsSubMap['imgUrl']=productImgUrl
|
491 |
productDetailsSubMap['imgUrl']=productImgUrl
|
| - |
|
492 |
'''
|
| 421 |
br1 = getBrowserObject()
|
493 |
br1 = getBrowserObject()
|
| 422 |
orderTrackingPage = br1.open(BASE_URL+subOrderTrackingUrl)
|
494 |
orderTrackingPage = br1.open(BASE_URL+'&'+subOrderTrackingParsingUrl)
|
| 423 |
headers = str(orderTrackingPage.info()).split('\n')
|
495 |
headers = str(orderTrackingPage.info()).split('\n')
|
| 424 |
orderTrackingPage= ungzipResponse(orderTrackingPage)
|
496 |
orderTrackingPage= ungzipResponse(orderTrackingPage)
|
| 425 |
jsonResponse = None
|
497 |
jsonResponse = None
|
| 426 |
for header in headers:
|
498 |
for header in headers:
|
| 427 |
header = header.split(':')
|
499 |
header = header.split(':')
|
| Line 431... |
Line 503... |
| 431 |
orderTrackingPageSoup = None
|
503 |
orderTrackingPageSoup = None
|
| 432 |
if jsonResponse is not None:
|
504 |
if jsonResponse is not None:
|
| 433 |
orderTrackingPageSoup = BeautifulSoup(str(jsonResponse['text']))
|
505 |
orderTrackingPageSoup = BeautifulSoup(str(jsonResponse['text']))
|
| 434 |
else:
|
506 |
else:
|
| 435 |
orderTrackingPageSoup = BeautifulSoup(orderTrackingPage)
|
507 |
orderTrackingPageSoup = BeautifulSoup(orderTrackingPage)
|
| 436 |
subOrderStatusList = orderTrackingPageSoup.findAll(attrs={'class' : 'price ord_status'})
|
508 |
subOrdersDetails = self.parseSingleSubOrder(orderTrackingPageSoup, emailId, subOrderId)
|
| 437 |
subOrderStatus = subOrderStatusList[0].contents[0].strip()
|
509 |
subOrders = list(set(subOrders + subOrdersDetails))
|
| 438 |
subOrderStatusTime= orderTrackingPageSoup.findAll(attrs={'class' : 'sts no_mobile'})[1].contents[2].strip()
|
- |
|
| 439 |
|
510 |
|
| 440 |
subOrder = SubOrder(productName, productUrl, placedOn, subtotal)
|
- |
|
| 441 |
subOrder.merchantSubOrderId = subOrderId
|
- |
|
| 442 |
subOrder.detailedStatus = subOrderStatus
|
- |
|
| 443 |
subOrder.imgUrl = productImgUrl
|
- |
|
| 444 |
subOrder.offerDiscount = discount*quantity
|
- |
|
| 445 |
subOrder.unitPrice = sellingPrice
|
- |
|
| 446 |
subOrder.productCode = productCode
|
- |
|
| 447 |
subOrder.amountPaid = subtotal
|
- |
|
| 448 |
subOrder.quantity = quantity
|
- |
|
| 449 |
|
- |
|
| 450 |
subOrders.append(subOrder)
|
511 |
return subOrders
|
| 451 |
|
- |
|
| 452 |
return self.updateCashbackInSubOrders(subOrders)
|
- |
|
| 453 |
|
512 |
|
| 454 |
def scrapeStoreOrders(self,):
|
513 |
def scrapeStoreOrders(self,):
|
| 455 |
#collectionMap = {'palcedOn':1}
|
514 |
#collectionMap = {'palcedOn':1}
|
| 456 |
searchMap = {}
|
515 |
searchMap = {}
|
| 457 |
collectionMap = {"orderTrackingUrl":1}
|
516 |
collectionMap = {"orderTrackingUrl":1}
|
| 458 |
orders = self._getActiveOrders(searchMap,collectionMap)
|
517 |
orders = self._getActiveOrders(searchMap,collectionMap)
|
| 459 |
for order in orders:
|
518 |
for order in orders:
|
| 460 |
print "Order", self.store_name, order['orderId'], order['orderTrackingUrl']
|
519 |
print "Order", self.store_name, order['orderId'], order['orderTrackingUrl']
|
| 461 |
url = order['orderTrackingUrl']
|
520 |
url = ORDER_TRACK_URL + order['orderTrackingUrl'].split('trackOrder?')[1]
|
| 462 |
page = fetchResponseUsingProxy(url)
|
521 |
page = fetchResponseUsingProxy(url)
|
| 463 |
soup = BeautifulSoup(page)
|
522 |
soup = BeautifulSoup(page)
|
| 464 |
bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
523 |
bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
| 465 |
closed = True
|
524 |
closed = True
|
| 466 |
orderStatusList = soup.findAll(attrs={'class' : 'price ord_status'})
|
525 |
orderStatusList = soup.findAll(attrs={'class' : 'price ord_status'})
|
| 467 |
if orderStatusList is not None and len(orderStatusList)>0:
|
526 |
if orderStatusList is not None and len(orderStatusList)>0:
|
| 468 |
subOrderId = soup.findAll(attrs={'class':'price ord_no'})[0].text.strip()
|
527 |
subOrderId = soup.findAll(attrs={'class':'price ord_no'})[0].text.strip()
|
| 469 |
subOrder = self._isSubOrderActive(order, subOrderId)
|
- |
|
| 470 |
orderStatus = orderStatusList[0].contents[0].strip()
|
528 |
orderStatus = orderStatusList[0].contents[0].strip()
|
| - |
|
529 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| 471 |
if subOrder is None:
|
530 |
orderTable.pop(0)
|
| 472 |
try:
|
531 |
count = 1
|
| 473 |
subOrder = self.parseSingleSubOrder(soup, order['orderTrackingUrl'].split('email_id=')[1], subOrderId, orderStatus)
|
- |
|
| 474 |
if subOrder is None:
|
532 |
while count <= len(orderTable):
|
| 475 |
continue
|
- |
|
| 476 |
self.db.merchantOrder.update({"orderId":order['orderId']},{'$push':{"subOrders":{"$each":todict([subOrder])}}})
|
- |
|
| 477 |
print "Added new suborders to Order id - ", order['orderId']
|
533 |
subOrder = self._isSubOrderActive(order, str(subOrderId)+'-'+str(count))
|
| 478 |
closed = False
|
534 |
count = count +1
|
| 479 |
except:
|
535 |
if subOrder is None:
|
| 480 |
pass
|
536 |
try:
|
| - |
|
537 |
subOrders = self.parseSingleSubOrder(soup, order['orderTrackingUrl'].split('email_id=')[1], subOrderId)
|
| 481 |
continue
|
538 |
for subOrder in subOrders:
|
| 482 |
elif subOrder['closed']:
|
539 |
if subOrder is None:
|
| 483 |
continue
|
540 |
continue
|
| 484 |
else:
|
- |
|
| 485 |
findMap = {"orderId": order['orderId'], "subOrders.merchantSubOrderId": subOrderId}
|
541 |
self.db.merchantOrder.update({"orderId":order['orderId']},{'$push':{"subOrders":{"$each":todict([subOrder])}}})
|
| 486 |
updateMap = {}
|
- |
|
| 487 |
updateMap["subOrders.$.detailedStatus"] = orderStatus
|
542 |
print "Added new suborders to Order id - ", order['orderId']
|
| 488 |
status = self._getStatusFromDetailedStatus(orderStatus)
|
543 |
closed = False
|
| 489 |
closedStatus = status in [Store.ORDER_DELIVERED, Store.ORDER_CANCELLED]
|
- |
|
| 490 |
if status is not None:
|
544 |
except:
|
| 491 |
updateMap["subOrders.$.status"] = status
|
545 |
pass
|
| 492 |
if closedStatus:
|
546 |
continue
|
| 493 |
#if status is closed then change the paybackStatus accordingly
|
- |
|
| 494 |
updateMap["subOrders.$.closed"] = True
|
547 |
elif subOrder['closed']:
|
| 495 |
if status == Store.ORDER_DELIVERED:
|
548 |
continue
|
| 496 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
- |
|
| 497 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_APPROVED
|
- |
|
| 498 |
elif status == Store.ORDER_CANCELLED:
|
- |
|
| 499 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
- |
|
| 500 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_CANCELLED
|
- |
|
| 501 |
else:
|
549 |
else:
|
| - |
|
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:
|
| 502 |
closed = False
|
567 |
closed = False
|
| 503 |
bulk.find(findMap).update({'$set' : updateMap})
|
568 |
bulk.find(findMap).update({'$set' : updateMap})
|
| 504 |
|
569 |
|
| 505 |
else:
|
570 |
else:
|
| 506 |
subOrdersList = self.parseMultiSubOrders(soup)
|
571 |
subOrdersList = self.parseMultiSubOrders(soup, order['orderTrackingUrl'].split('email_id=')[1])
|
| 507 |
for subOrderObj in subOrdersList:
|
572 |
for subOrderObj in subOrdersList:
|
| 508 |
subOrder = self._isSubOrderActive(order, subOrderObj.merchantSubOrderId)
|
573 |
subOrder = self._isSubOrderActive(order, subOrderObj.merchantSubOrderId)
|
| 509 |
if subOrder is None:
|
574 |
if subOrder is None:
|
| 510 |
self.db.merchantOrder.update({"orderId":order['orderId']},{'$push':{"subOrders":{"$each":todict([subOrderObj])}}})
|
575 |
self.db.merchantOrder.update({"orderId":order['orderId']},{'$push':{"subOrders":{"$each":todict([subOrderObj])}}})
|
| 511 |
print "Added new suborders to Order id - ", order['orderId']
|
576 |
print "Added new suborders to Order id - ", order['orderId']
|
| Line 534... |
Line 599... |
| 534 |
closed = False
|
599 |
closed = False
|
| 535 |
bulk.find(findMap).update({'$set' : updateMap})
|
600 |
bulk.find(findMap).update({'$set' : updateMap})
|
| 536 |
bulk.find({'orderId': order['orderId']}).update({'$set':{'closed': closed,"parseError":False}})
|
601 |
bulk.find({'orderId': order['orderId']}).update({'$set':{'closed': closed,"parseError":False}})
|
| 537 |
result = bulk.execute()
|
602 |
result = bulk.execute()
|
| 538 |
tprint(result)
|
603 |
tprint(result)
|
| - |
|
604 |
|
| - |
|
605 |
'''
|
| - |
|
606 |
def getTrackingUrls(self, userId):
|
| - |
|
607 |
missingOrderUrls = ['https://sm.shopclues.com/myaccount','https://sm.shopclues.com/myorders']
|
| - |
|
608 |
return missingOrderUrls
|
| 539 |
|
609 |
|
| 540 |
def saveToAffiliate(self, offers):
|
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() !='':
|
| 541 |
raise NotImplementedError
|
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'
|
| - |
|
622 |
|
| - |
|
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 |
|
| 542 |
|
634 |
|
| 543 |
def todict(obj, classkey=None):
|
635 |
def todict(obj, classkey=None):
|
| 544 |
if isinstance(obj, dict):
|
636 |
if isinstance(obj, dict):
|
| 545 |
data = {}
|
637 |
data = {}
|
| 546 |
for (k, v) in obj.items():
|
638 |
for (k, v) in obj.items():
|
| Line 556... |
Line 648... |
| 556 |
if not callable(value) and not key.startswith('_')])
|
648 |
if not callable(value) and not key.startswith('_')])
|
| 557 |
if classkey is not None and hasattr(obj, "__class__"):
|
649 |
if classkey is not None and hasattr(obj, "__class__"):
|
| 558 |
data[classkey] = obj.__class__.__name__
|
650 |
data[classkey] = obj.__class__.__name__
|
| 559 |
return data
|
651 |
return data
|
| 560 |
else:
|
652 |
else:
|
| 561 |
return obj
|
653 |
return obj
|
| - |
|
654 |
|
| 562 |
|
655 |
|
| 563 |
|
656 |
|