| 13828 |
kshitij.so |
1 |
import urllib2
|
|
|
2 |
import simplejson as json
|
|
|
3 |
import pymongo
|
| 15270 |
kshitij.so |
4 |
from dtr.utils.utils import to_java_date, getNlcPoints
|
| 13917 |
kshitij.so |
5 |
from datetime import datetime, timedelta
|
| 13828 |
kshitij.so |
6 |
import time
|
| 14180 |
kshitij.so |
7 |
from multiprocessing import Pool as ThreadPool
|
|
|
8 |
from multiprocessing import cpu_count
|
| 14254 |
kshitij.so |
9 |
import optparse
|
| 14325 |
kshitij.so |
10 |
from dtr.storage.MemCache import MemCache
|
| 14705 |
kshitij.so |
11 |
from dtr.utils.utils import getCashBack
|
| 15270 |
kshitij.so |
12 |
import traceback
|
|
|
13 |
from operator import itemgetter
|
| 13828 |
kshitij.so |
14 |
|
|
|
15 |
con = None
|
|
|
16 |
|
| 14254 |
kshitij.so |
17 |
parser = optparse.OptionParser()
|
|
|
18 |
parser.add_option("-m", "--m", dest="mongoHost",
|
|
|
19 |
default="localhost",
|
|
|
20 |
type="string", help="The HOST where the mongo server is running",
|
|
|
21 |
metavar="mongo_host")
|
|
|
22 |
|
|
|
23 |
(options, args) = parser.parse_args()
|
|
|
24 |
|
| 14325 |
kshitij.so |
25 |
mc = MemCache(options.mongoHost)
|
| 14254 |
kshitij.so |
26 |
|
| 13828 |
kshitij.so |
27 |
headers = {
|
|
|
28 |
'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
|
|
|
29 |
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
|
|
30 |
'Accept-Language' : 'en-US,en;q=0.8',
|
|
|
31 |
'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
|
|
|
32 |
}
|
|
|
33 |
|
| 14254 |
kshitij.so |
34 |
def get_mongo_connection(host=options.mongoHost, port=27017):
|
| 13828 |
kshitij.so |
35 |
global con
|
|
|
36 |
if con is None:
|
|
|
37 |
print "Establishing connection %s host and port %d" %(host,port)
|
|
|
38 |
try:
|
|
|
39 |
con = pymongo.MongoClient(host, port)
|
|
|
40 |
except Exception, e:
|
|
|
41 |
print e
|
|
|
42 |
return None
|
|
|
43 |
return con
|
|
|
44 |
|
| 14180 |
kshitij.so |
45 |
def populate():
|
|
|
46 |
toScrapMap = {}
|
| 14132 |
kshitij.so |
47 |
bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0}}))
|
|
|
48 |
for bestSeller in bestSellers:
|
|
|
49 |
snapdealBestSellers = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':3}))
|
|
|
50 |
for data in snapdealBestSellers:
|
| 14180 |
kshitij.so |
51 |
if not toScrapMap.has_key(data['_id']):
|
| 15270 |
kshitij.so |
52 |
data['dealFlag'] = 0
|
|
|
53 |
data['dealType'] = 0
|
|
|
54 |
data['dealPoints'] = 0
|
|
|
55 |
data['manualDealThresholdPrice'] = None
|
| 14180 |
kshitij.so |
56 |
toScrapMap[data['_id']] = data
|
| 14252 |
kshitij.so |
57 |
dealFlagged = list(get_mongo_connection().Catalog.Deals.find({'source_id':3,'showDeal':1,'totalPoints':{'$gt':0}}))
|
|
|
58 |
for deal in dealFlagged:
|
|
|
59 |
if not toScrapMap.has_key(deal['_id']):
|
| 14261 |
kshitij.so |
60 |
data = list(get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']}))
|
| 15270 |
kshitij.so |
61 |
data[0]['dealFlag'] = 0
|
|
|
62 |
data[0]['dealType'] = 0
|
|
|
63 |
data[0]['dealPoints'] = 0
|
|
|
64 |
data[0]['manualDealThresholdPrice'] = None
|
| 14261 |
kshitij.so |
65 |
toScrapMap[deal['_id']] = data[0]
|
| 15270 |
kshitij.so |
66 |
manualDeals = list(get_mongo_connection().Catalog.ManualDeals.find({'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())},'source_id':3}))
|
|
|
67 |
for manualDeal in manualDeals:
|
|
|
68 |
if not toScrapMap.has_key(manualDeal['sku']):
|
|
|
69 |
data = list(get_mongo_connection().Catalog.MasterData.find({'_id':manualDeal['sku']}))
|
|
|
70 |
if len(data) > 0:
|
|
|
71 |
data[0]['dealFlag'] = 1
|
|
|
72 |
data[0]['dealType'] = manualDeal['dealType']
|
|
|
73 |
data[0]['dealPoints'] = manualDeal['dealPoints']
|
|
|
74 |
data[0]['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
|
|
|
75 |
toScrapMap[manualDeal['sku']] = data[0]
|
|
|
76 |
else:
|
|
|
77 |
data = toScrapMap.get(manualDeal['sku'])
|
|
|
78 |
data['dealFlag'] = 1
|
|
|
79 |
data['dealType'] = manualDeal['dealType']
|
|
|
80 |
data['dealPoints'] = manualDeal['dealPoints']
|
|
|
81 |
data['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
|
| 14180 |
kshitij.so |
82 |
pool = ThreadPool(cpu_count() *2)
|
|
|
83 |
pool.map(updatePrices,toScrapMap.values())
|
|
|
84 |
pool.close()
|
|
|
85 |
pool.join()
|
| 14252 |
kshitij.so |
86 |
print "joining threads at %s"%(str(datetime.now()))
|
| 14180 |
kshitij.so |
87 |
|
|
|
88 |
|
|
|
89 |
def updatePrices(data):
|
|
|
90 |
if data['source_id']!=3:
|
|
|
91 |
return
|
|
|
92 |
print data['identifier']
|
|
|
93 |
if data['identifier'] is None or len(data['identifier'].strip())==0:
|
|
|
94 |
print "returning"
|
|
|
95 |
return
|
|
|
96 |
|
|
|
97 |
try:
|
|
|
98 |
if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):
|
|
|
99 |
print "sku id is already updated",data['_id']
|
|
|
100 |
return
|
|
|
101 |
except:
|
|
|
102 |
pass
|
|
|
103 |
|
| 15823 |
kshitij.so |
104 |
url="http://www.snapdeal.com/acors/json/v2/gvbps?supc=%s&catUrl=&bn=&catId=175&start=0&count=10000"%(data['identifier'].strip())
|
| 14180 |
kshitij.so |
105 |
print url
|
|
|
106 |
time.sleep(1)
|
|
|
107 |
lowestOfferPrice = 0
|
|
|
108 |
instock = 0
|
| 15270 |
kshitij.so |
109 |
buyBoxPrice = 0
|
|
|
110 |
isBuyBox = 1
|
|
|
111 |
stock = 0
|
| 14180 |
kshitij.so |
112 |
req = urllib2.Request(url,headers=headers)
|
|
|
113 |
response = urllib2.urlopen(req)
|
| 15820 |
kshitij.so |
114 |
try:
|
|
|
115 |
vendorInfo = json.load(response)
|
|
|
116 |
except:
|
|
|
117 |
return
|
|
|
118 |
finally:
|
|
|
119 |
response.close()
|
| 15270 |
kshitij.so |
120 |
|
| 15820 |
kshitij.so |
121 |
try:
|
|
|
122 |
buyBoxStock = vendorInfo['primaryVendor']['buyableInventory']
|
|
|
123 |
if buyBoxStock >0:
|
|
|
124 |
buyBoxPrice = vendorInfo['primaryVendor']['sellingPrice']
|
|
|
125 |
except:
|
|
|
126 |
pass
|
|
|
127 |
|
|
|
128 |
sortedVendorsData = sorted(vendorInfo['vendors'], key=itemgetter('sellingPrice'))
|
|
|
129 |
for sortedVendorData in sortedVendorsData:
|
|
|
130 |
lowestOfferPrice = float(sortedVendorData['sellingPrice'])
|
|
|
131 |
try:
|
|
|
132 |
stock = sortedVendorData['buyableInventory']
|
|
|
133 |
except:
|
|
|
134 |
pass
|
|
|
135 |
if stock > 0 and lowestOfferPrice > 0:
|
|
|
136 |
instock = 1
|
|
|
137 |
break
|
|
|
138 |
if buyBoxPrice != lowestOfferPrice:
|
|
|
139 |
isBuyBox = 0
|
|
|
140 |
|
| 14180 |
kshitij.so |
141 |
print lowestOfferPrice
|
|
|
142 |
print instock
|
| 14181 |
kshitij.so |
143 |
print "Lowest Offer Price for id %d is %d , stock is %d and stock count is %d" %(data['_id'],lowestOfferPrice,instock,stock)
|
| 14180 |
kshitij.so |
144 |
print "*************"
|
|
|
145 |
if instock == 1:
|
| 15270 |
kshitij.so |
146 |
get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice,'updatedOn':to_java_date(datetime.now()),'priceUpdatedOn':to_java_date(datetime.now()),'in_stock':instock,'buyBoxFlag':isBuyBox}}, multi=True)
|
| 14180 |
kshitij.so |
147 |
get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':instock}}, multi=True)
|
|
|
148 |
else:
|
| 15270 |
kshitij.so |
149 |
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)
|
| 14180 |
kshitij.so |
150 |
get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock}}, multi=True)
|
|
|
151 |
|
|
|
152 |
try:
|
| 15270 |
kshitij.so |
153 |
recomputeDeal(data)
|
| 14180 |
kshitij.so |
154 |
except:
|
|
|
155 |
print "Unable to compute deal for ",data['skuBundleId']
|
|
|
156 |
|
| 14325 |
kshitij.so |
157 |
|
|
|
158 |
def populateNegativeDeals():
|
|
|
159 |
negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
|
| 15270 |
kshitij.so |
160 |
mc.set("negative_deals", negativeDeals, 600)
|
|
|
161 |
|
|
|
162 |
def recomputePoints(item, deal):
|
|
|
163 |
try:
|
|
|
164 |
nlcPoints = getNlcPoints(item, deal['minNlc'], deal['maxNlc'], deal['available_price'])
|
|
|
165 |
except:
|
|
|
166 |
traceback.print_exc()
|
|
|
167 |
nlcPoints = deal['nlcPoints']
|
|
|
168 |
if item['manualDealThresholdPrice'] >= deal['available_price']:
|
|
|
169 |
dealPoints = item['dealPoints']
|
|
|
170 |
else:
|
|
|
171 |
dealPoints = 0
|
|
|
172 |
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']}})
|
|
|
173 |
|
| 14180 |
kshitij.so |
174 |
|
| 15270 |
kshitij.so |
175 |
def recomputeDeal(item):
|
| 13917 |
kshitij.so |
176 |
"""Lets recompute deal for this bundle"""
|
| 15270 |
kshitij.so |
177 |
print "Recomputing for bundleId",item.get('skuBundleId')
|
|
|
178 |
skuBundleId = item['skuBundleId']
|
| 13917 |
kshitij.so |
179 |
|
|
|
180 |
similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
|
|
|
181 |
bestPrice = float("inf")
|
|
|
182 |
bestOne = None
|
|
|
183 |
bestSellerPoints = 0
|
|
|
184 |
toUpdate = []
|
|
|
185 |
for similarItem in similarItems:
|
| 14330 |
kshitij.so |
186 |
if mc.get("negative_deals") is None:
|
| 14325 |
kshitij.so |
187 |
populateNegativeDeals()
|
| 15270 |
kshitij.so |
188 |
# try:
|
|
|
189 |
# cashBack = getCashBack(similarItem['_id'], similarItem['source_id'], similarItem['category_id'], mc, options.mongoHost)
|
|
|
190 |
# if not cashBack or cashBack.get('cash_back_status')!=1:
|
|
|
191 |
# pass
|
|
|
192 |
# else:
|
|
|
193 |
# if cashBack['cash_back_type'] ==1:
|
|
|
194 |
# similarItem['available_price'] = similarItem['available_price'] - similarItem['available_price'] * float(cashBack['cash_back'])/100
|
|
|
195 |
# elif cashBack['cash_back_type'] ==2:
|
|
|
196 |
# similarItem['available_price'] = similarItem['available_price'] - float(cashBack['cash_back'])
|
|
|
197 |
# else:
|
|
|
198 |
# pass
|
|
|
199 |
# except Exception as cashBackEx:
|
|
|
200 |
# print cashBackEx
|
|
|
201 |
# print "Error calculating cashback."
|
|
|
202 |
if similarItem['_id'] == item['_id']:
|
|
|
203 |
try:
|
|
|
204 |
recomputePoints(item, similarItem)
|
|
|
205 |
except:
|
|
|
206 |
traceback.print_exc()
|
| 14330 |
kshitij.so |
207 |
if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
|
| 13917 |
kshitij.so |
208 |
get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
|
|
|
209 |
continue
|
|
|
210 |
if similarItem['available_price'] < bestPrice:
|
|
|
211 |
bestOne = similarItem
|
|
|
212 |
bestPrice = similarItem['available_price']
|
|
|
213 |
bestSellerPoints = similarItem['bestSellerPoints']
|
|
|
214 |
elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
|
|
|
215 |
bestOne = similarItem
|
|
|
216 |
bestPrice = similarItem['available_price']
|
|
|
217 |
bestSellerPoints = similarItem['bestSellerPoints']
|
|
|
218 |
else:
|
|
|
219 |
pass
|
|
|
220 |
if bestOne is not None:
|
|
|
221 |
for similarItem in similarItems:
|
|
|
222 |
toUpdate.append(similarItem['_id'])
|
|
|
223 |
toUpdate.remove(bestOne['_id'])
|
|
|
224 |
get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
|
|
|
225 |
if len(toUpdate) > 0:
|
|
|
226 |
get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
|
|
|
227 |
|
| 13828 |
kshitij.so |
228 |
def main():
|
| 14180 |
kshitij.so |
229 |
populate()
|
| 13828 |
kshitij.so |
230 |
|
|
|
231 |
if __name__=='__main__':
|
|
|
232 |
main()
|