| 16407 |
kshitij.so |
1 |
import pymongo
|
|
|
2 |
from dtr.utils.utils import to_java_date, getNlcPoints
|
|
|
3 |
from datetime import datetime, timedelta
|
|
|
4 |
from operator import itemgetter
|
|
|
5 |
from dtr.utils import PaytmOfferScraper, PaytmScraper
|
|
|
6 |
from multiprocessing import Pool as ThreadPool
|
|
|
7 |
from multiprocessing import cpu_count
|
|
|
8 |
import optparse
|
|
|
9 |
from dtr.storage.MemCache import MemCache
|
| 20347 |
kshitij.so |
10 |
from dtr.utils.utils import getCashBack, DEAL_PRIORITY
|
| 16407 |
kshitij.so |
11 |
import traceback
|
| 16414 |
kshitij.so |
12 |
from dtr.CouponMaster import addToPaytmMaster
|
| 16417 |
kshitij.so |
13 |
from dtr.storage import DataService
|
| 16407 |
kshitij.so |
14 |
|
|
|
15 |
con = None
|
|
|
16 |
|
|
|
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 |
|
|
|
25 |
mc = MemCache(options.mongoHost)
|
|
|
26 |
|
| 16417 |
kshitij.so |
27 |
DataService.initialize(db_hostname=options.mongoHost)
|
|
|
28 |
|
| 16407 |
kshitij.so |
29 |
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4, 'SHOPCLUES.COM':5,'PAYTM.COM':6}
|
|
|
30 |
|
| 19190 |
kshitij.so |
31 |
def getNetPriceForItem(itemId, source_id, category_id ,price):
|
|
|
32 |
cash_back_type = 0
|
|
|
33 |
cash_back = 0
|
|
|
34 |
try:
|
|
|
35 |
cashBack = getCashBack(itemId, source_id, category_id, mc, options.mongoHost)
|
|
|
36 |
if not cashBack or cashBack.get('cash_back_status')!=1:
|
|
|
37 |
cash_back_type = 0
|
|
|
38 |
cash_back = 0
|
|
|
39 |
|
|
|
40 |
else:
|
|
|
41 |
if cashBack['cash_back_type'] in (1,2):
|
|
|
42 |
|
|
|
43 |
if cashBack.get('maxCashBack') is not None:
|
|
|
44 |
|
|
|
45 |
if cashBack.get('cash_back_type') ==1 and (float(cashBack.get('cash_back'))*price)/100 > cashBack.get('maxCashBack'):
|
|
|
46 |
cashBack['cash_back_type'] = 2
|
|
|
47 |
cashBack['cash_back'] = cashBack['maxCashBack']
|
|
|
48 |
elif cashBack.get('cash_back_type') ==2 and cashBack.get('cash_back') > cashBack.get('maxCashBack'):
|
|
|
49 |
cashBack['cash_back'] = cashBack['maxCashBack']
|
|
|
50 |
else:
|
|
|
51 |
pass
|
|
|
52 |
|
|
|
53 |
|
|
|
54 |
|
|
|
55 |
cash_back_type = cashBack['cash_back_type']
|
|
|
56 |
cash_back = float(cashBack['cash_back'])
|
|
|
57 |
except Exception as cashBackEx:
|
|
|
58 |
pass
|
|
|
59 |
|
|
|
60 |
if cash_back_type ==1:
|
|
|
61 |
return (price - float(cash_back)*price/100)
|
|
|
62 |
elif cash_back_type ==2:
|
|
|
63 |
return (price - cash_back)
|
|
|
64 |
else:
|
|
|
65 |
return price
|
|
|
66 |
|
|
|
67 |
|
| 16407 |
kshitij.so |
68 |
def get_mongo_connection(host=options.mongoHost, port=27017):
|
|
|
69 |
global con
|
|
|
70 |
if con is None:
|
|
|
71 |
print "Establishing connection %s host and port %d" %(host,port)
|
|
|
72 |
try:
|
|
|
73 |
con = pymongo.MongoClient(host, port)
|
|
|
74 |
except Exception, e:
|
|
|
75 |
print e
|
|
|
76 |
return None
|
|
|
77 |
return con
|
|
|
78 |
|
|
|
79 |
def populate():
|
|
|
80 |
toScrapMap = {}
|
|
|
81 |
bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0}}))
|
|
|
82 |
for bestSeller in bestSellers:
|
|
|
83 |
paytmBestSellers = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':6}))
|
|
|
84 |
for data in paytmBestSellers:
|
|
|
85 |
if not toScrapMap.has_key(data['_id']):
|
|
|
86 |
data['dealFlag'] = 0
|
|
|
87 |
data['dealType'] = 0
|
|
|
88 |
toScrapMap[data['_id']] = data
|
|
|
89 |
dealFlagged = list(get_mongo_connection().Catalog.Deals.find({'source_id':6,'showDeal':1,'totalPoints':{'$gt':-100}}))
|
|
|
90 |
for deal in dealFlagged:
|
|
|
91 |
if not toScrapMap.has_key(deal['_id']):
|
|
|
92 |
data = list(get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']}))
|
|
|
93 |
data[0]['dealFlag'] = 0
|
|
|
94 |
data[0]['dealType'] = 0
|
|
|
95 |
toScrapMap[deal['_id']] = data[0]
|
|
|
96 |
manualDeals = list(get_mongo_connection().Catalog.ManualDeals.find({'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())},'source_id':6}))
|
|
|
97 |
for manualDeal in manualDeals:
|
|
|
98 |
if not toScrapMap.has_key(manualDeal['sku']):
|
|
|
99 |
data = list(get_mongo_connection().Catalog.MasterData.find({'_id':manualDeal['sku']}))
|
|
|
100 |
if len(data) > 0:
|
|
|
101 |
data[0]['dealFlag'] = 1
|
|
|
102 |
data[0]['dealType'] = manualDeal['dealType']
|
|
|
103 |
toScrapMap[manualDeal['sku']] = data[0]
|
|
|
104 |
else:
|
|
|
105 |
data = toScrapMap.get(manualDeal['sku'])
|
|
|
106 |
data['dealFlag'] = 1
|
|
|
107 |
data['dealType'] = manualDeal['dealType']
|
| 16414 |
kshitij.so |
108 |
for val in toScrapMap.values():
|
|
|
109 |
scrapePaytm(val)
|
| 16407 |
kshitij.so |
110 |
print "joining threads at %s"%(str(datetime.now()))
|
|
|
111 |
|
|
|
112 |
def scrapePaytm(data):
|
|
|
113 |
if data['source_id']!=6:
|
|
|
114 |
return
|
|
|
115 |
if data['identifier'] is None or len(data['identifier'].strip())==0:
|
|
|
116 |
print "returning in valid identifier"
|
|
|
117 |
return
|
|
|
118 |
|
| 16506 |
kshitij.so |
119 |
if data.get('ignorePricing') ==1:
|
| 16407 |
kshitij.so |
120 |
print "Ignored items returning for %d"%(data['_id'])
|
| 16506 |
kshitij.so |
121 |
return
|
|
|
122 |
|
| 16407 |
kshitij.so |
123 |
|
|
|
124 |
try:
|
|
|
125 |
if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):
|
|
|
126 |
print "sku id is already updated %d" %(data['_id'])
|
|
|
127 |
return
|
|
|
128 |
except:
|
|
|
129 |
pass
|
|
|
130 |
|
|
|
131 |
paytmScraper = PaytmScraper.PaytmScraper()
|
|
|
132 |
url = "https://catalog.paytm.com/v1/mobile/product/%s"%(data['identifier'].strip())
|
|
|
133 |
try:
|
|
|
134 |
result = paytmScraper.read(url)
|
| 16414 |
kshitij.so |
135 |
print result
|
| 16407 |
kshitij.so |
136 |
effective_price = result.get('offerPrice')
|
| 16463 |
kshitij.so |
137 |
gross_price = effective_price
|
| 16407 |
kshitij.so |
138 |
coupon = ""
|
| 18283 |
kshitij.so |
139 |
shareUrl = result.get('shareUrl')
|
|
|
140 |
if shareUrl is None:
|
|
|
141 |
shareUrl = data['marketPlaceUrl']
|
| 16414 |
kshitij.so |
142 |
print result['offerUrl']
|
| 16407 |
kshitij.so |
143 |
try:
|
|
|
144 |
offers = PaytmOfferScraper.fetchOffers(result['offerUrl'])
|
|
|
145 |
bestOffer = {}
|
|
|
146 |
for offer_data in offers.get('codes'):
|
| 16414 |
kshitij.so |
147 |
if effective_price > offer_data.get('effective_price'):
|
| 16407 |
kshitij.so |
148 |
effective_price = offer_data.get('effective_price')
|
|
|
149 |
bestOffer = offer_data
|
|
|
150 |
coupon = bestOffer.get('code')
|
|
|
151 |
except:
|
| 16414 |
kshitij.so |
152 |
traceback.print_exc()
|
|
|
153 |
print "coupon code",coupon
|
| 16470 |
kshitij.so |
154 |
if len(coupon) > 0:
|
|
|
155 |
result['codAvailable'] = 0
|
| 16407 |
kshitij.so |
156 |
available_price = effective_price
|
|
|
157 |
if result['inStock']:
|
| 19190 |
kshitij.so |
158 |
if result['codAvailable'] ==0:
|
|
|
159 |
netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('PAYTM.COM'), data['category_id'], gross_price)
|
|
|
160 |
else:
|
|
|
161 |
netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('PAYTM.COM'), data['category_id'], available_price)
|
|
|
162 |
|
| 18283 |
kshitij.so |
163 |
get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':available_price,'updatedOn':to_java_date(datetime.now()),'priceUpdatedOn':to_java_date(datetime.now()),'in_stock':1,'buyBoxFlag':1,'codAvailable':result.get('codAvailable'),'coupon':coupon,'gross_price':gross_price,'marketPlaceUrl':shareUrl}})
|
| 19190 |
kshitij.so |
164 |
get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':available_price , 'in_stock':1,'codAvailable':result.get('codAvailable'),'gross_price':gross_price,'netPriceAfterCashBack':netPriceAfterCashBack}})
|
| 16407 |
kshitij.so |
165 |
else:
|
| 19190 |
kshitij.so |
166 |
if data['codAvailable'] ==0:
|
|
|
167 |
netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('PAYTM.COM'), data['category_id'], data['gross_price'])
|
|
|
168 |
else:
|
|
|
169 |
netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('PAYTM.COM'), data['category_id'], data['available_price'])
|
|
|
170 |
|
| 18283 |
kshitij.so |
171 |
get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(datetime.now()),'in_stock':0,'priceUpdatedOn':to_java_date(datetime.now()),'buyBoxFlag':1,'codAvailable':result.get('codAvailable'),'coupon':coupon,'marketPlaceUrl':shareUrl}})
|
| 19190 |
kshitij.so |
172 |
get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0,'codAvailable':result.get('codAvailable'),'netPriceAfterCashBack':netPriceAfterCashBack}})
|
| 16407 |
kshitij.so |
173 |
|
|
|
174 |
except:
|
| 19190 |
kshitij.so |
175 |
if data['codAvailable'] ==0:
|
|
|
176 |
netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('PAYTM.COM'), data['category_id'], data['gross_price'])
|
|
|
177 |
else:
|
|
|
178 |
netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('PAYTM.COM'), data['category_id'], data['available_price'])
|
|
|
179 |
|
|
|
180 |
|
| 16407 |
kshitij.so |
181 |
get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(datetime.now()),'in_stock':0,'priceUpdatedOn':to_java_date(datetime.now()),'buyBoxFlag':1}})
|
| 19190 |
kshitij.so |
182 |
get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0,'netPriceAfterCashBack':netPriceAfterCashBack}})
|
| 16407 |
kshitij.so |
183 |
|
|
|
184 |
|
|
|
185 |
try:
|
|
|
186 |
recomputeDeal(data)
|
|
|
187 |
except:
|
|
|
188 |
print "Unable to compute deal for %s"%(data['skuBundleId'])
|
|
|
189 |
|
| 16506 |
kshitij.so |
190 |
#def recomputePoints(item, deal):
|
|
|
191 |
# try:
|
|
|
192 |
# if item.get('available_price') == deal['available_price']:
|
|
|
193 |
# print "No need to compute points for %d , as price is still same" %(item['_id'])
|
|
|
194 |
# return
|
|
|
195 |
# nlcPoints = getNlcPoints(item, deal['minNlc'], deal['maxNlc'], deal['available_price'])
|
|
|
196 |
# except:
|
|
|
197 |
# print traceback.print_exc()
|
|
|
198 |
# nlcPoints = deal['nlcPoints']
|
|
|
199 |
#
|
|
|
200 |
# bundleDealPoints = list(get_mongo_connection().Catalog.DealPoints.find({'skuBundleId':item['skuBundleId'],'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())}}))
|
|
|
201 |
# if len(bundleDealPoints) > 0:
|
|
|
202 |
# item['manualDealThresholdPrice'] = bundleDealPoints[0]['dealThresholdPrice']
|
|
|
203 |
# dealPoints = bundleDealPoints[0]['dealPoints']
|
|
|
204 |
# else:
|
|
|
205 |
# dealPoints = 0
|
|
|
206 |
# item['manualDealThresholdPrice'] = None
|
|
|
207 |
#
|
|
|
208 |
# 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']}})
|
| 16407 |
kshitij.so |
209 |
|
|
|
210 |
def populateNegativeDeals():
|
|
|
211 |
negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
|
|
|
212 |
mc.set("negative_deals", negativeDeals, 600)
|
|
|
213 |
|
|
|
214 |
def recomputeDeal(item):
|
|
|
215 |
"""Lets recompute deal for this bundle"""
|
|
|
216 |
print "Recomputing for bundleId %d" %(item.get('skuBundleId'))
|
|
|
217 |
skuBundleId = item['skuBundleId']
|
|
|
218 |
|
| 19190 |
kshitij.so |
219 |
similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('netPriceAfterCashBack',pymongo.ASCENDING)]))
|
| 16407 |
kshitij.so |
220 |
bestPrice = float("inf")
|
|
|
221 |
bestOne = None
|
|
|
222 |
toUpdate = []
|
|
|
223 |
prepaidBestPrice = float("inf")
|
|
|
224 |
prepaidBestOne = None
|
|
|
225 |
for similarItem in similarItems:
|
|
|
226 |
if similarItem['codAvailable'] ==1:
|
|
|
227 |
if mc.get("negative_deals") is None:
|
|
|
228 |
populateNegativeDeals()
|
|
|
229 |
if similarItem['in_stock'] == 0 or similarItem['_id'] in mc.get("negative_deals"):
|
|
|
230 |
get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
|
|
|
231 |
continue
|
|
|
232 |
if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
|
|
|
233 |
get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
|
|
|
234 |
continue
|
| 19190 |
kshitij.so |
235 |
if similarItem.get('netPriceAfterCashBack') < bestPrice:
|
| 16407 |
kshitij.so |
236 |
bestOne = similarItem
|
| 19190 |
kshitij.so |
237 |
bestPrice = similarItem.get('netPriceAfterCashBack')
|
| 20347 |
kshitij.so |
238 |
elif similarItem.get('netPriceAfterCashBack') == bestPrice:
|
|
|
239 |
|
|
|
240 |
try:
|
|
|
241 |
if (DEAL_PRIORITY.index(int(similarItem['source_id'])) > DEAL_PRIORITY.index(int(bestOne['source_id']))):
|
|
|
242 |
continue
|
|
|
243 |
except:
|
|
|
244 |
traceback.print_exc()
|
|
|
245 |
|
| 16407 |
kshitij.so |
246 |
bestOne = similarItem
|
| 19190 |
kshitij.so |
247 |
bestPrice = similarItem.get('netPriceAfterCashBack')
|
| 16407 |
kshitij.so |
248 |
else:
|
|
|
249 |
pass
|
|
|
250 |
else:
|
|
|
251 |
if mc.get("negative_deals") is None:
|
|
|
252 |
populateNegativeDeals()
|
|
|
253 |
if similarItem['in_stock'] == 0 or similarItem['_id'] in mc.get("negative_deals"):
|
|
|
254 |
get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
|
|
|
255 |
continue
|
|
|
256 |
if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
|
|
|
257 |
get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
|
|
|
258 |
continue
|
| 19190 |
kshitij.so |
259 |
if similarItem.get('netPriceAfterCashBack') < prepaidBestPrice:
|
| 16407 |
kshitij.so |
260 |
prepaidBestOne = similarItem
|
| 19190 |
kshitij.so |
261 |
prepaidBestPrice = similarItem.get('netPriceAfterCashBack')
|
| 20347 |
kshitij.so |
262 |
elif similarItem.get('netPriceAfterCashBack') == prepaidBestPrice:
|
|
|
263 |
|
|
|
264 |
try:
|
| 20365 |
kshitij.so |
265 |
if (DEAL_PRIORITY.index(int(similarItem['source_id'])) > DEAL_PRIORITY.index(int(prepaidBestOne['source_id']))):
|
| 20347 |
kshitij.so |
266 |
continue
|
|
|
267 |
except:
|
|
|
268 |
traceback.print_exc()
|
|
|
269 |
|
| 16407 |
kshitij.so |
270 |
prepaidBestOne = similarItem
|
| 19190 |
kshitij.so |
271 |
prepaidBestPrice = similarItem.get('netPriceAfterCashBack')
|
| 16407 |
kshitij.so |
272 |
else:
|
|
|
273 |
pass
|
|
|
274 |
if bestOne is not None or prepaidBestOne is not None:
|
|
|
275 |
for similarItem in similarItems:
|
|
|
276 |
toUpdate.append(similarItem['_id'])
|
|
|
277 |
if bestOne is not None:
|
|
|
278 |
toUpdate.remove(bestOne['_id'])
|
|
|
279 |
get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})
|
|
|
280 |
if prepaidBestOne is not None:
|
|
|
281 |
if bestOne is not None:
|
| 19190 |
kshitij.so |
282 |
if prepaidBestOne.get('netPriceAfterCashBack') < bestOne.get('netPriceAfterCashBack'):
|
| 16407 |
kshitij.so |
283 |
toUpdate.remove(prepaidBestOne['_id'])
|
|
|
284 |
get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
|
|
|
285 |
else:
|
|
|
286 |
toUpdate.remove(prepaidBestOne['_id'])
|
|
|
287 |
get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
|
|
|
288 |
if len(toUpdate) > 0:
|
|
|
289 |
get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)
|
|
|
290 |
|
| 19190 |
kshitij.so |
291 |
|
| 16407 |
kshitij.so |
292 |
def main():
|
|
|
293 |
populate()
|
|
|
294 |
|
|
|
295 |
if __name__=='__main__':
|
|
|
296 |
main()
|