| 13828 |
kshitij.so |
1 |
import pymongo
|
| 15269 |
kshitij.so |
2 |
from dtr.utils.utils import to_java_date, getNlcPoints
|
| 13915 |
kshitij.so |
3 |
from datetime import datetime, timedelta
|
| 13828 |
kshitij.so |
4 |
from operator import itemgetter
|
| 14123 |
kshitij.so |
5 |
from dtr.utils import FlipkartScraper,NewFlipkartScraper
|
| 14178 |
kshitij.so |
6 |
from multiprocessing import Pool as ThreadPool
|
| 14172 |
kshitij.so |
7 |
from multiprocessing import cpu_count
|
| 14255 |
kshitij.so |
8 |
import optparse
|
| 14325 |
kshitij.so |
9 |
from dtr.storage.MemCache import MemCache
|
| 14705 |
kshitij.so |
10 |
from dtr.utils.utils import getCashBack
|
| 15269 |
kshitij.so |
11 |
import traceback
|
| 13828 |
kshitij.so |
12 |
|
|
|
13 |
con = None
|
|
|
14 |
|
| 14255 |
kshitij.so |
15 |
parser = optparse.OptionParser()
|
|
|
16 |
parser.add_option("-m", "--m", dest="mongoHost",
|
|
|
17 |
default="localhost",
|
|
|
18 |
type="string", help="The HOST where the mongo server is running",
|
|
|
19 |
metavar="mongo_host")
|
|
|
20 |
|
|
|
21 |
(options, args) = parser.parse_args()
|
|
|
22 |
|
| 14325 |
kshitij.so |
23 |
mc = MemCache(options.mongoHost)
|
|
|
24 |
|
| 16328 |
kshitij.so |
25 |
ignoreItems = [23364, 477, 476]
|
| 16019 |
kshitij.so |
26 |
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4, 'SHOPCLUES.COM':5}
|
| 15610 |
kshitij.so |
27 |
|
| 14255 |
kshitij.so |
28 |
def get_mongo_connection(host=options.mongoHost, port=27017):
|
| 13828 |
kshitij.so |
29 |
global con
|
|
|
30 |
if con is None:
|
|
|
31 |
print "Establishing connection %s host and port %d" %(host,port)
|
|
|
32 |
try:
|
|
|
33 |
con = pymongo.MongoClient(host, port)
|
|
|
34 |
except Exception, e:
|
|
|
35 |
print e
|
|
|
36 |
return None
|
|
|
37 |
return con
|
|
|
38 |
|
| 14149 |
kshitij.so |
39 |
def populate():
|
|
|
40 |
toScrapMap = {}
|
| 14131 |
kshitij.so |
41 |
bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0}}))
|
|
|
42 |
for bestSeller in bestSellers:
|
| 14149 |
kshitij.so |
43 |
amazonBestSellers = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':2}))
|
|
|
44 |
for data in amazonBestSellers:
|
|
|
45 |
if not toScrapMap.has_key(data['_id']):
|
| 15269 |
kshitij.so |
46 |
data['dealFlag'] = 0
|
|
|
47 |
data['dealType'] = 0
|
|
|
48 |
data['dealPoints'] = 0
|
|
|
49 |
data['manualDealThresholdPrice'] = None
|
| 14149 |
kshitij.so |
50 |
toScrapMap[data['_id']] = data
|
| 16175 |
kshitij.so |
51 |
dealFlagged = list(get_mongo_connection().Catalog.Deals.find({'source_id':2,'showDeal':1,'totalPoints':{'$gt':-100}}))
|
| 14251 |
kshitij.so |
52 |
for deal in dealFlagged:
|
|
|
53 |
if not toScrapMap.has_key(deal['_id']):
|
| 14262 |
kshitij.so |
54 |
data = list(get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']}))
|
| 15269 |
kshitij.so |
55 |
data[0]['dealFlag'] = 0
|
|
|
56 |
data[0]['dealType'] = 0
|
|
|
57 |
data[0]['dealPoints'] = 0
|
|
|
58 |
data[0]['manualDealThresholdPrice'] = None
|
| 14262 |
kshitij.so |
59 |
toScrapMap[deal['_id']] = data[0]
|
| 15269 |
kshitij.so |
60 |
manualDeals = list(get_mongo_connection().Catalog.ManualDeals.find({'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())},'source_id':2}))
|
|
|
61 |
for manualDeal in manualDeals:
|
|
|
62 |
if not toScrapMap.has_key(manualDeal['sku']):
|
|
|
63 |
data = list(get_mongo_connection().Catalog.MasterData.find({'_id':manualDeal['sku']}))
|
|
|
64 |
if len(data) > 0:
|
|
|
65 |
data[0]['dealFlag'] = 1
|
|
|
66 |
data[0]['dealType'] = manualDeal['dealType']
|
|
|
67 |
data[0]['dealPoints'] = manualDeal['dealPoints']
|
|
|
68 |
data[0]['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
|
|
|
69 |
toScrapMap[manualDeal['sku']] = data[0]
|
|
|
70 |
else:
|
|
|
71 |
data = toScrapMap.get(manualDeal['sku'])
|
|
|
72 |
data['dealFlag'] = 1
|
|
|
73 |
data['dealType'] = manualDeal['dealType']
|
|
|
74 |
data['dealPoints'] = manualDeal['dealPoints']
|
|
|
75 |
data['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
|
| 14178 |
kshitij.so |
76 |
pool = ThreadPool(cpu_count() *2)
|
| 14149 |
kshitij.so |
77 |
pool.map(scrapeFlipkart,toScrapMap.values())
|
|
|
78 |
pool.close()
|
|
|
79 |
pool.join()
|
| 14251 |
kshitij.so |
80 |
print "joining threads at %s"%(str(datetime.now()))
|
| 14149 |
kshitij.so |
81 |
|
|
|
82 |
def scrapeFlipkart(data):
|
|
|
83 |
if data['source_id']!=2:
|
| 14157 |
kshitij.so |
84 |
return
|
| 14149 |
kshitij.so |
85 |
retryCount = 0
|
|
|
86 |
if data['identifier'] is None or len(data['identifier'].strip())==0:
|
| 14157 |
kshitij.so |
87 |
print "returning in valid identifier"
|
|
|
88 |
return
|
| 14149 |
kshitij.so |
89 |
|
| 15610 |
kshitij.so |
90 |
if data['_id'] in ignoreItems:
|
|
|
91 |
print "Ignored items returning for %d"%(data['_id'])
|
|
|
92 |
return
|
|
|
93 |
|
| 14149 |
kshitij.so |
94 |
try:
|
|
|
95 |
if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):
|
| 15269 |
kshitij.so |
96 |
print "sku id is already updated %d" %(data['_id'])
|
| 14157 |
kshitij.so |
97 |
return
|
| 14149 |
kshitij.so |
98 |
except:
|
|
|
99 |
pass
|
|
|
100 |
|
|
|
101 |
|
|
|
102 |
lowestSp = 0
|
|
|
103 |
inStock = 0
|
| 15269 |
kshitij.so |
104 |
buyBoxPrice = 0
|
|
|
105 |
isBuyBox = 0
|
| 14157 |
kshitij.so |
106 |
scraperFk = FlipkartScraper.FlipkartScraper()
|
|
|
107 |
scraperProductPage = NewFlipkartScraper.FlipkartProductPageScraper()
|
| 14149 |
kshitij.so |
108 |
try:
|
|
|
109 |
if data['marketPlaceUrl']!="" or data['marketPlaceUrl'] !="http://www.flipkart.com/ps/%s"%(data['identifier']):
|
|
|
110 |
result = scraperProductPage.read(data['marketPlaceUrl'])
|
|
|
111 |
if result.get('lowestSp')!=0:
|
|
|
112 |
lowestSp = result.get('lowestSp')
|
|
|
113 |
inStock = result.get('inStock')
|
| 15269 |
kshitij.so |
114 |
buyBoxPrice = result.get('buyBoxPrice')
|
| 14149 |
kshitij.so |
115 |
except:
|
| 15269 |
kshitij.so |
116 |
print "Unable to scrape product page %s" %(data['identifier'])
|
| 14149 |
kshitij.so |
117 |
|
|
|
118 |
|
|
|
119 |
if lowestSp == 0:
|
|
|
120 |
url = "http://www.flipkart.com/ps/%s"%(data['identifier'].strip())
|
|
|
121 |
while(retryCount < 3):
|
| 14131 |
kshitij.so |
122 |
try:
|
| 15269 |
kshitij.so |
123 |
vendorsData, buyBoxInfo = (scraperFk.read(url))
|
| 14149 |
kshitij.so |
124 |
fetched = True
|
|
|
125 |
break
|
|
|
126 |
except Exception as e:
|
|
|
127 |
print "***Retry count ",retryCount
|
|
|
128 |
retryCount+=1
|
|
|
129 |
if retryCount == 3:
|
|
|
130 |
fetched = False
|
|
|
131 |
print e
|
|
|
132 |
if not fetched:
|
| 15269 |
kshitij.so |
133 |
print "Unable to fetch data after multiple tries.Continue for %s"%(data['identifier'])
|
| 14157 |
kshitij.so |
134 |
return
|
| 14149 |
kshitij.so |
135 |
|
|
|
136 |
sortedVendorsData = []
|
|
|
137 |
sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
|
|
|
138 |
print "data",sortedVendorsData
|
|
|
139 |
lowestSp, iterator = (0,)*2
|
|
|
140 |
for vData in sortedVendorsData:
|
|
|
141 |
if iterator == 0:
|
|
|
142 |
lowestSp = vData['sellingPrice']
|
|
|
143 |
break
|
|
|
144 |
if lowestSp > 0:
|
|
|
145 |
inStock = 1
|
| 15269 |
kshitij.so |
146 |
if len(buyBoxInfo) > 0:
|
|
|
147 |
buyBoxPrice = buyBoxInfo[0].get('sellingPrice')
|
|
|
148 |
else:
|
|
|
149 |
print "No info about buy box for %d"%(data.get('_id'))
|
| 14149 |
kshitij.so |
150 |
print lowestSp
|
|
|
151 |
print inStock
|
| 15269 |
kshitij.so |
152 |
if buyBoxPrice is not None and buyBoxPrice == lowestSp:
|
|
|
153 |
isBuyBox = 1
|
| 14149 |
kshitij.so |
154 |
if lowestSp > 0:
|
| 15269 |
kshitij.so |
155 |
get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp,'updatedOn':to_java_date(datetime.now()),'priceUpdatedOn':to_java_date(datetime.now()),'in_stock':inStock,'buyBoxFlag':isBuyBox}}, multi=True)
|
| 16019 |
kshitij.so |
156 |
get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp , 'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
|
| 14149 |
kshitij.so |
157 |
else:
|
| 15269 |
kshitij.so |
158 |
get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(datetime.now()),'in_stock':inStock,'priceUpdatedOn':to_java_date(datetime.now()),'buyBoxFlag':isBuyBox}}, multi=True)
|
| 16019 |
kshitij.so |
159 |
get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock,'codAvailable':data['codAvailable']}})
|
| 14149 |
kshitij.so |
160 |
|
|
|
161 |
try:
|
| 15269 |
kshitij.so |
162 |
recomputeDeal(data)
|
| 14149 |
kshitij.so |
163 |
except:
|
| 15269 |
kshitij.so |
164 |
print "Unable to compute deal for %s"%(data['skuBundleId'])
|
| 13828 |
kshitij.so |
165 |
|
| 15269 |
kshitij.so |
166 |
def recomputePoints(item, deal):
|
|
|
167 |
try:
|
| 15344 |
kshitij.so |
168 |
if item.get('available_price') == deal['available_price']:
|
|
|
169 |
print "No need to compute points for %d , as price is still same" %(item['_id'])
|
|
|
170 |
raise
|
| 15269 |
kshitij.so |
171 |
nlcPoints = getNlcPoints(item, deal['minNlc'], deal['maxNlc'], deal['available_price'])
|
|
|
172 |
except:
|
|
|
173 |
print traceback.print_exc()
|
|
|
174 |
nlcPoints = deal['nlcPoints']
|
|
|
175 |
if item['manualDealThresholdPrice'] >= deal['available_price']:
|
|
|
176 |
dealPoints = item['dealPoints']
|
|
|
177 |
else:
|
|
|
178 |
dealPoints = 0
|
|
|
179 |
get_mongo_connection().Catalog.Deals.update({'_id':deal['_id']},{"$set":{'totalPoints':deal['totalPoints'] - deal['nlcPoints'] + nlcPoints - deal['dealPoints'] +dealPoints , 'nlcPoints': nlcPoints, 'dealPoints': dealPoints, 'manualDealThresholdPrice': item['manualDealThresholdPrice']}})
|
|
|
180 |
|
| 14325 |
kshitij.so |
181 |
def populateNegativeDeals():
|
|
|
182 |
negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
|
|
|
183 |
mc.set("negative_deals", negativeDeals, 600)
|
|
|
184 |
|
| 15269 |
kshitij.so |
185 |
def recomputeDeal(item):
|
| 13915 |
kshitij.so |
186 |
"""Lets recompute deal for this bundle"""
|
| 15269 |
kshitij.so |
187 |
print "Recomputing for bundleId %d" %(item.get('skuBundleId'))
|
|
|
188 |
skuBundleId = item['skuBundleId']
|
| 13915 |
kshitij.so |
189 |
|
|
|
190 |
similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
|
|
|
191 |
bestPrice = float("inf")
|
|
|
192 |
bestOne = None
|
|
|
193 |
bestSellerPoints = 0
|
|
|
194 |
toUpdate = []
|
| 16019 |
kshitij.so |
195 |
prepaidBestPrice = float("inf")
|
|
|
196 |
prepaidBestOne = None
|
|
|
197 |
prepaidBestSellerPoints = 0
|
| 13915 |
kshitij.so |
198 |
for similarItem in similarItems:
|
| 15269 |
kshitij.so |
199 |
if similarItem['_id'] == item['_id']:
|
| 16019 |
kshitij.so |
200 |
try:
|
|
|
201 |
recomputePoints(item, similarItem)
|
|
|
202 |
except:
|
|
|
203 |
traceback.print_exc()
|
|
|
204 |
if similarItem['codAvailable'] ==1:
|
|
|
205 |
if mc.get("negative_deals") is None:
|
|
|
206 |
populateNegativeDeals()
|
| 16175 |
kshitij.so |
207 |
if similarItem['in_stock'] == 0 or similarItem['_id'] in mc.get("negative_deals"):
|
| 16019 |
kshitij.so |
208 |
get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
|
|
|
209 |
continue
|
|
|
210 |
if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
|
|
|
211 |
get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
|
|
|
212 |
continue
|
|
|
213 |
if similarItem['available_price'] < bestPrice:
|
|
|
214 |
bestOne = similarItem
|
|
|
215 |
bestPrice = similarItem['available_price']
|
|
|
216 |
bestSellerPoints = similarItem['bestSellerPoints']
|
|
|
217 |
elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
|
|
|
218 |
bestOne = similarItem
|
|
|
219 |
bestPrice = similarItem['available_price']
|
|
|
220 |
bestSellerPoints = similarItem['bestSellerPoints']
|
|
|
221 |
else:
|
|
|
222 |
pass
|
| 13915 |
kshitij.so |
223 |
else:
|
| 16019 |
kshitij.so |
224 |
if mc.get("negative_deals") is None:
|
|
|
225 |
populateNegativeDeals()
|
| 16175 |
kshitij.so |
226 |
if similarItem['in_stock'] == 0 or similarItem['_id'] in mc.get("negative_deals"):
|
| 16019 |
kshitij.so |
227 |
get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
|
|
|
228 |
continue
|
|
|
229 |
if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
|
|
|
230 |
get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
|
|
|
231 |
continue
|
|
|
232 |
if similarItem['available_price'] < prepaidBestPrice:
|
|
|
233 |
prepaidBestOne = similarItem
|
|
|
234 |
prepaidBestPrice = similarItem['available_price']
|
|
|
235 |
prepaidBestSellerPoints = similarItem['bestSellerPoints']
|
|
|
236 |
elif similarItem['available_price'] == prepaidBestPrice and prepaidBestSellerPoints < similarItem['bestSellerPoints']:
|
|
|
237 |
prepaidBestOne = similarItem
|
|
|
238 |
prepaidBestPrice = similarItem['available_price']
|
|
|
239 |
prepaidBestSellerPoints = similarItem['bestSellerPoints']
|
|
|
240 |
else:
|
|
|
241 |
pass
|
| 16026 |
kshitij.so |
242 |
if bestOne is not None or prepaidBestOne is not None:
|
| 13915 |
kshitij.so |
243 |
for similarItem in similarItems:
|
|
|
244 |
toUpdate.append(similarItem['_id'])
|
| 16026 |
kshitij.so |
245 |
if bestOne is not None:
|
|
|
246 |
toUpdate.remove(bestOne['_id'])
|
|
|
247 |
get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})
|
|
|
248 |
if prepaidBestOne is not None:
|
| 16074 |
kshitij.so |
249 |
if bestOne is not None:
|
|
|
250 |
if prepaidBestOne['available_price'] < bestOne['available_price']:
|
|
|
251 |
toUpdate.remove(prepaidBestOne['_id'])
|
|
|
252 |
get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
|
|
|
253 |
else:
|
|
|
254 |
toUpdate.remove(prepaidBestOne['_id'])
|
|
|
255 |
get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
|
| 13915 |
kshitij.so |
256 |
if len(toUpdate) > 0:
|
| 16019 |
kshitij.so |
257 |
get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)
|
| 13915 |
kshitij.so |
258 |
|
| 13828 |
kshitij.so |
259 |
def main():
|
| 14157 |
kshitij.so |
260 |
populate()
|
| 13828 |
kshitij.so |
261 |
|
|
|
262 |
if __name__=='__main__':
|
|
|
263 |
main()
|