| Line 1... |
Line 1... |
| 1 |
import pymongo
|
1 |
import pymongo
|
| 2 |
from dtr.utils.utils import to_java_date
|
2 |
from dtr.utils.utils import to_java_date, getNlcPoints
|
| 3 |
from datetime import datetime, timedelta
|
3 |
from datetime import datetime, timedelta
|
| 4 |
from operator import itemgetter
|
4 |
from operator import itemgetter
|
| 5 |
from dtr.utils import FlipkartScraper,NewFlipkartScraper
|
5 |
from dtr.utils import FlipkartScraper,NewFlipkartScraper
|
| 6 |
from multiprocessing import Pool as ThreadPool
|
6 |
from multiprocessing import Pool as ThreadPool
|
| 7 |
from multiprocessing import cpu_count
|
7 |
from multiprocessing import cpu_count
|
| 8 |
import optparse
|
8 |
import optparse
|
| 9 |
from dtr.storage.MemCache import MemCache
|
9 |
from dtr.storage.MemCache import MemCache
|
| 10 |
from dtr.utils.utils import getCashBack
|
10 |
from dtr.utils.utils import getCashBack
|
| - |
|
11 |
import traceback
|
| 11 |
|
12 |
|
| 12 |
con = None
|
13 |
con = None
|
| 13 |
|
14 |
|
| 14 |
parser = optparse.OptionParser()
|
15 |
parser = optparse.OptionParser()
|
| 15 |
parser.add_option("-m", "--m", dest="mongoHost",
|
16 |
parser.add_option("-m", "--m", dest="mongoHost",
|
| Line 37... |
Line 38... |
| 37 |
bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0}}))
|
38 |
bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0}}))
|
| 38 |
for bestSeller in bestSellers:
|
39 |
for bestSeller in bestSellers:
|
| 39 |
amazonBestSellers = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':2}))
|
40 |
amazonBestSellers = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':2}))
|
| 40 |
for data in amazonBestSellers:
|
41 |
for data in amazonBestSellers:
|
| 41 |
if not toScrapMap.has_key(data['_id']):
|
42 |
if not toScrapMap.has_key(data['_id']):
|
| - |
|
43 |
data['dealFlag'] = 0
|
| - |
|
44 |
data['dealType'] = 0
|
| - |
|
45 |
data['dealPoints'] = 0
|
| - |
|
46 |
data['manualDealThresholdPrice'] = None
|
| 42 |
toScrapMap[data['_id']] = data
|
47 |
toScrapMap[data['_id']] = data
|
| 43 |
dealFlagged = list(get_mongo_connection().Catalog.Deals.find({'source_id':2,'showDeal':1,'totalPoints':{'$gt':0}}))
|
48 |
dealFlagged = list(get_mongo_connection().Catalog.Deals.find({'source_id':2,'showDeal':1,'totalPoints':{'$gt':0}}))
|
| 44 |
for deal in dealFlagged:
|
49 |
for deal in dealFlagged:
|
| 45 |
if not toScrapMap.has_key(deal['_id']):
|
50 |
if not toScrapMap.has_key(deal['_id']):
|
| 46 |
data = list(get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']}))
|
51 |
data = list(get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']}))
|
| - |
|
52 |
data[0]['dealFlag'] = 0
|
| - |
|
53 |
data[0]['dealType'] = 0
|
| - |
|
54 |
data[0]['dealPoints'] = 0
|
| - |
|
55 |
data[0]['manualDealThresholdPrice'] = None
|
| 47 |
toScrapMap[deal['_id']] = data[0]
|
56 |
toScrapMap[deal['_id']] = data[0]
|
| - |
|
57 |
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}))
|
| - |
|
58 |
for manualDeal in manualDeals:
|
| - |
|
59 |
if not toScrapMap.has_key(manualDeal['sku']):
|
| - |
|
60 |
data = list(get_mongo_connection().Catalog.MasterData.find({'_id':manualDeal['sku']}))
|
| - |
|
61 |
if len(data) > 0:
|
| - |
|
62 |
data[0]['dealFlag'] = 1
|
| - |
|
63 |
data[0]['dealType'] = manualDeal['dealType']
|
| - |
|
64 |
data[0]['dealPoints'] = manualDeal['dealPoints']
|
| - |
|
65 |
data[0]['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
|
| - |
|
66 |
toScrapMap[manualDeal['sku']] = data[0]
|
| - |
|
67 |
else:
|
| - |
|
68 |
data = toScrapMap.get(manualDeal['sku'])
|
| - |
|
69 |
data['dealFlag'] = 1
|
| - |
|
70 |
data['dealType'] = manualDeal['dealType']
|
| - |
|
71 |
data['dealPoints'] = manualDeal['dealPoints']
|
| - |
|
72 |
data['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
|
| 48 |
pool = ThreadPool(cpu_count() *2)
|
73 |
pool = ThreadPool(cpu_count() *2)
|
| 49 |
pool.map(scrapeFlipkart,toScrapMap.values())
|
74 |
pool.map(scrapeFlipkart,toScrapMap.values())
|
| 50 |
pool.close()
|
75 |
pool.close()
|
| 51 |
pool.join()
|
76 |
pool.join()
|
| 52 |
print "joining threads at %s"%(str(datetime.now()))
|
77 |
print "joining threads at %s"%(str(datetime.now()))
|
| 53 |
|
78 |
|
| 54 |
def scrapeFlipkart(data):
|
79 |
def scrapeFlipkart(data):
|
| 55 |
if data['source_id']!=2:
|
80 |
if data['source_id']!=2:
|
| 56 |
return
|
81 |
return
|
| 57 |
retryCount = 0
|
82 |
retryCount = 0
|
| 58 |
print str(data['identifier'])
|
- |
|
| 59 |
if data['identifier'] is None or len(data['identifier'].strip())==0:
|
83 |
if data['identifier'] is None or len(data['identifier'].strip())==0:
|
| 60 |
print "returning in valid identifier"
|
84 |
print "returning in valid identifier"
|
| 61 |
return
|
85 |
return
|
| 62 |
|
86 |
|
| 63 |
try:
|
87 |
try:
|
| 64 |
if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):
|
88 |
if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):
|
| 65 |
print "sku id is already updated",data['_id']
|
89 |
print "sku id is already updated %d" %(data['_id'])
|
| 66 |
return
|
90 |
return
|
| 67 |
except:
|
91 |
except:
|
| 68 |
pass
|
92 |
pass
|
| 69 |
|
93 |
|
| 70 |
|
94 |
|
| 71 |
lowestSp = 0
|
95 |
lowestSp = 0
|
| 72 |
inStock = 0
|
96 |
inStock = 0
|
| - |
|
97 |
buyBoxPrice = 0
|
| - |
|
98 |
isBuyBox = 0
|
| 73 |
scraperFk = FlipkartScraper.FlipkartScraper()
|
99 |
scraperFk = FlipkartScraper.FlipkartScraper()
|
| 74 |
scraperProductPage = NewFlipkartScraper.FlipkartProductPageScraper()
|
100 |
scraperProductPage = NewFlipkartScraper.FlipkartProductPageScraper()
|
| 75 |
try:
|
101 |
try:
|
| 76 |
if data['marketPlaceUrl']!="" or data['marketPlaceUrl'] !="http://www.flipkart.com/ps/%s"%(data['identifier']):
|
102 |
if data['marketPlaceUrl']!="" or data['marketPlaceUrl'] !="http://www.flipkart.com/ps/%s"%(data['identifier']):
|
| 77 |
result = scraperProductPage.read(data['marketPlaceUrl'])
|
103 |
result = scraperProductPage.read(data['marketPlaceUrl'])
|
| 78 |
if result.get('lowestSp')!=0:
|
104 |
if result.get('lowestSp')!=0:
|
| 79 |
lowestSp = result.get('lowestSp')
|
105 |
lowestSp = result.get('lowestSp')
|
| 80 |
inStock = result.get('inStock')
|
106 |
inStock = result.get('inStock')
|
| - |
|
107 |
buyBoxPrice = result.get('buyBoxPrice')
|
| 81 |
except:
|
108 |
except:
|
| 82 |
print "Unable to scrape product page ",data['identifier']
|
109 |
print "Unable to scrape product page %s" %(data['identifier'])
|
| 83 |
|
110 |
|
| 84 |
|
111 |
|
| 85 |
if lowestSp == 0:
|
112 |
if lowestSp == 0:
|
| 86 |
url = "http://www.flipkart.com/ps/%s"%(data['identifier'].strip())
|
113 |
url = "http://www.flipkart.com/ps/%s"%(data['identifier'].strip())
|
| 87 |
while(retryCount < 3):
|
114 |
while(retryCount < 3):
|
| 88 |
try:
|
115 |
try:
|
| 89 |
vendorsData = scraperFk.read(url)
|
116 |
vendorsData, buyBoxInfo = (scraperFk.read(url))
|
| 90 |
fetched = True
|
117 |
fetched = True
|
| 91 |
break
|
118 |
break
|
| 92 |
except Exception as e:
|
119 |
except Exception as e:
|
| 93 |
print "***Retry count ",retryCount
|
120 |
print "***Retry count ",retryCount
|
| 94 |
retryCount+=1
|
121 |
retryCount+=1
|
| 95 |
if retryCount == 3:
|
122 |
if retryCount == 3:
|
| 96 |
fetched = False
|
123 |
fetched = False
|
| 97 |
print e
|
124 |
print e
|
| 98 |
if not fetched:
|
125 |
if not fetched:
|
| 99 |
print "Unable to fetch data after multiple tries.Continue for ",data['identifier']
|
126 |
print "Unable to fetch data after multiple tries.Continue for %s"%(data['identifier'])
|
| 100 |
return
|
127 |
return
|
| 101 |
|
128 |
|
| 102 |
sortedVendorsData = []
|
129 |
sortedVendorsData = []
|
| 103 |
sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
|
130 |
sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
|
| 104 |
print "data",sortedVendorsData
|
131 |
print "data",sortedVendorsData
|
| Line 107... |
Line 134... |
| 107 |
if iterator == 0:
|
134 |
if iterator == 0:
|
| 108 |
lowestSp = vData['sellingPrice']
|
135 |
lowestSp = vData['sellingPrice']
|
| 109 |
break
|
136 |
break
|
| 110 |
if lowestSp > 0:
|
137 |
if lowestSp > 0:
|
| 111 |
inStock = 1
|
138 |
inStock = 1
|
| - |
|
139 |
if len(buyBoxInfo) > 0:
|
| - |
|
140 |
buyBoxPrice = buyBoxInfo[0].get('sellingPrice')
|
| - |
|
141 |
else:
|
| - |
|
142 |
print "No info about buy box for %d"%(data.get('_id'))
|
| 112 |
print lowestSp
|
143 |
print lowestSp
|
| 113 |
print inStock
|
144 |
print inStock
|
| - |
|
145 |
if buyBoxPrice is not None and buyBoxPrice == lowestSp:
|
| - |
|
146 |
isBuyBox = 1
|
| 114 |
if lowestSp > 0:
|
147 |
if lowestSp > 0:
|
| 115 |
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}}, multi=True)
|
148 |
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)
|
| 116 |
get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp , 'in_stock':inStock}}, multi=True)
|
149 |
get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp , 'in_stock':inStock}}, multi=True)
|
| 117 |
else:
|
150 |
else:
|
| 118 |
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())}}, multi=True)
|
151 |
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)
|
| 119 |
get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock}}, multi=True)
|
152 |
get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock}}, multi=True)
|
| 120 |
|
153 |
|
| 121 |
try:
|
154 |
try:
|
| 122 |
recomputeDeal(data['skuBundleId'])
|
155 |
recomputeDeal(data)
|
| 123 |
except:
|
156 |
except:
|
| 124 |
print "Unable to compute deal for ",data['skuBundleId']
|
157 |
print "Unable to compute deal for %s"%(data['skuBundleId'])
|
| - |
|
158 |
|
| - |
|
159 |
def recomputePoints(item, deal):
|
| - |
|
160 |
try:
|
| - |
|
161 |
nlcPoints = getNlcPoints(item, deal['minNlc'], deal['maxNlc'], deal['available_price'])
|
| - |
|
162 |
except:
|
| - |
|
163 |
print traceback.print_exc()
|
| - |
|
164 |
nlcPoints = deal['nlcPoints']
|
| - |
|
165 |
if item['manualDealThresholdPrice'] >= deal['available_price']:
|
| - |
|
166 |
dealPoints = item['dealPoints']
|
| - |
|
167 |
else:
|
| - |
|
168 |
dealPoints = 0
|
| - |
|
169 |
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']}})
|
| - |
|
170 |
|
| - |
|
171 |
|
| 125 |
|
172 |
|
| 126 |
def populateNegativeDeals():
|
173 |
def populateNegativeDeals():
|
| 127 |
negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
|
174 |
negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
|
| 128 |
mc.set("negative_deals", negativeDeals, 600)
|
175 |
mc.set("negative_deals", negativeDeals, 600)
|
| 129 |
|
176 |
|
| 130 |
def recomputeDeal(skuBundleId):
|
177 |
def recomputeDeal(item):
|
| 131 |
"""Lets recompute deal for this bundle"""
|
178 |
"""Lets recompute deal for this bundle"""
|
| 132 |
print "Recomputing for bundleId",skuBundleId
|
179 |
print "Recomputing for bundleId %d" %(item.get('skuBundleId'))
|
| - |
|
180 |
skuBundleId = item['skuBundleId']
|
| 133 |
|
181 |
|
| 134 |
similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
|
182 |
similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
|
| 135 |
bestPrice = float("inf")
|
183 |
bestPrice = float("inf")
|
| 136 |
bestOne = None
|
184 |
bestOne = None
|
| 137 |
bestSellerPoints = 0
|
185 |
bestSellerPoints = 0
|
| 138 |
toUpdate = []
|
186 |
toUpdate = []
|
| 139 |
for similarItem in similarItems:
|
187 |
for similarItem in similarItems:
|
| 140 |
if mc.get("negative_deals") is None:
|
188 |
if mc.get("negative_deals") is None:
|
| 141 |
populateNegativeDeals()
|
189 |
populateNegativeDeals()
|
| 142 |
try:
|
190 |
# try:
|
| 143 |
cashBack = getCashBack(similarItem['_id'], similarItem['source_id'], similarItem['category_id'], mc, options.mongoHost)
|
191 |
# cashBack = getCashBack(similarItem['_id'], similarItem['source_id'], similarItem['category_id'], mc, options.mongoHost)
|
| 144 |
if not cashBack or cashBack.get('cash_back_status')!=1:
|
192 |
# if not cashBack or cashBack.get('cash_back_status')!=1:
|
| 145 |
pass
|
193 |
# pass
|
| 146 |
else:
|
194 |
# else:
|
| 147 |
if cashBack['cash_back_type'] ==1:
|
195 |
# if cashBack['cash_back_type'] ==1:
|
| 148 |
similarItem['available_price'] = similarItem['available_price'] - similarItem['available_price'] * float(cashBack['cash_back'])/100
|
196 |
# similarItem['available_price'] = similarItem['available_price'] - similarItem['available_price'] * float(cashBack['cash_back'])/100
|
| 149 |
elif cashBack['cash_back_type'] ==2:
|
197 |
# elif cashBack['cash_back_type'] ==2:
|
| 150 |
similarItem['available_price'] = similarItem['available_price'] - float(cashBack['cash_back'])
|
198 |
# similarItem['available_price'] = similarItem['available_price'] - float(cashBack['cash_back'])
|
| 151 |
else:
|
199 |
# else:
|
| 152 |
pass
|
200 |
# pass
|
| 153 |
except Exception as cashBackEx:
|
201 |
# except Exception as cashBackEx:
|
| 154 |
print cashBackEx
|
202 |
# print cashBackEx
|
| 155 |
print "Error calculating cashback."
|
203 |
# print "Error calculating cashback."
|
| - |
|
204 |
if similarItem['_id'] == item['_id']:
|
| - |
|
205 |
recomputePoints(item, similarItem)
|
| 156 |
if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
|
206 |
if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
|
| 157 |
get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
|
207 |
get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
|
| 158 |
continue
|
208 |
continue
|
| 159 |
if similarItem['available_price'] < bestPrice:
|
209 |
if similarItem['available_price'] < bestPrice:
|
| 160 |
bestOne = similarItem
|
210 |
bestOne = similarItem
|