Rev 17107 | Rev 20347 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
import urllib2import simplejson as jsonimport pymongofrom dtr.utils.utils import to_java_date, getNlcPointsfrom datetime import datetime, timedeltaimport timefrom multiprocessing import Pool as ThreadPoolfrom multiprocessing import cpu_countimport optparsefrom dtr.storage.MemCache import MemCachefrom dtr.utils.utils import getCashBack, get_mongo_connection, SOURCE_MAPimport tracebackfrom operator import itemgetterimport chardetfrom dtr.utils import HomeShop18ScraperSOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4, 'SHOPCLUES.COM':5,'PAYTM.COM':6, 'HOMESHOP18.COM':7}con = Noneparser = optparse.OptionParser()parser.add_option("-m", "--m", dest="mongoHost",default="localhost",type="string", help="The HOST where the mongo server is running",metavar="mongo_host")(options, args) = parser.parse_args()mc = MemCache(options.mongoHost)def getNetPriceForItem(itemId, source_id, category_id ,price):cash_back_type = 0cash_back = 0try:cashBack = getCashBack(itemId, source_id, category_id, mc, options.mongoHost)if not cashBack or cashBack.get('cash_back_status')!=1:cash_back_type = 0cash_back = 0else:if cashBack['cash_back_type'] in (1,2):if cashBack.get('maxCashBack') is not None:if cashBack.get('cash_back_type') ==1 and (float(cashBack.get('cash_back'))*price)/100 > cashBack.get('maxCashBack'):cashBack['cash_back_type'] = 2cashBack['cash_back'] = cashBack['maxCashBack']elif cashBack.get('cash_back_type') ==2 and cashBack.get('cash_back') > cashBack.get('maxCashBack'):cashBack['cash_back'] = cashBack['maxCashBack']else:passcash_back_type = cashBack['cash_back_type']cash_back = float(cashBack['cash_back'])except Exception as cashBackEx:passif cash_back_type ==1:return (price - float(cash_back)*price/100)elif cash_back_type ==2:return (price - cash_back)else:return pricedef populate():toScrapMap = {}bestSellers = list(get_mongo_connection(host=options.mongoHost).Catalog.MasterData.find({'rank':{'$gt':0}}))for bestSeller in bestSellers:snapdealBestSellers = list(get_mongo_connection(host=options.mongoHost).Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':7}))for data in snapdealBestSellers:if not toScrapMap.has_key(data['_id']):data['dealFlag'] = 0data['dealType'] = 0toScrapMap[data['_id']] = datadealFlagged = list(get_mongo_connection(host=options.mongoHost).Catalog.Deals.find({'source_id':7,'showDeal':1,'totalPoints':{'$gt':-100}}))for deal in dealFlagged:if not toScrapMap.has_key(deal['_id']):data = list(get_mongo_connection(host=options.mongoHost).Catalog.MasterData.find({'_id':deal['_id']}))data[0]['dealFlag'] = 0data[0]['dealType'] = 0toScrapMap[deal['_id']] = data[0]manualDeals = list(get_mongo_connection(host=options.mongoHost).Catalog.ManualDeals.find({'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())},'source_id':7}))for manualDeal in manualDeals:if not toScrapMap.has_key(manualDeal['sku']):data = list(get_mongo_connection(host=options.mongoHost).Catalog.MasterData.find({'_id':manualDeal['sku']}))if len(data) > 0:data[0]['dealFlag'] = 1data[0]['dealType'] = manualDeal['dealType']toScrapMap[manualDeal['sku']] = data[0]else:data = toScrapMap.get(manualDeal['sku'])data['dealFlag'] = 1data['dealType'] = manualDeal['dealType']for val in toScrapMap.values():updatePrices(val)def updatePrices(data):if data.get('ignorePricing') ==1:print "Ignored items returning for %d"%(data['_id'])returnif data['source_id']!=7:returnprint data['identifier']if data['identifier'] is None or len(data['identifier'].strip())==0:print "returning"returntry:if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):print "sku id is already updated",data['_id']returnexcept:passresult = Nonetry:url = 'http://m.homeshop18.com/product.mobi?productId='+str(data['identifier'])scraper = HomeShop18Scraper.HomeShop18Scraper()result = scraper.read(url)except:print "Unable to scrape %d"%(data['_id'])get_mongo_connection(host=options.mongoHost).Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(datetime.now()),'in_stock':0,'priceUpdatedOn':to_java_date(datetime.now())}})get_mongo_connection(host=options.mongoHost).Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0}})returninStock = 0lowestOfferPrice = 0if result is not None:lowestOfferPrice = float(result['price']+result['shippingCharge'])inStock = result['inStock']print lowestOfferPriceprint inStockprint "*************"if lowestOfferPrice ==0:inStock = 0if inStock == 1:netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('HOMESHOP18.COM'), data['category_id'], lowestOfferPrice)get_mongo_connection(host=options.mongoHost).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}}, multi=True)get_mongo_connection(host=options.mongoHost).Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':inStock,'codAvailable':data['codAvailable'],'netPriceAfterCashBack':netPriceAfterCashBack}}, multi=True)else:lowestOfferPrice = data['available_price']netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('HOMESHOP18.COM'), data['category_id'], lowestOfferPrice)get_mongo_connection(host=options.mongoHost).Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(datetime.now()),'in_stock':inStock,'priceUpdatedOn':to_java_date(datetime.now())}}, multi=True)get_mongo_connection(host=options.mongoHost).Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock,'codAvailable':data['codAvailable'],'netPriceAfterCashBack':netPriceAfterCashBack}}, multi=True)try:recomputeDeal(data)except:print "Unable to compute deal for ",data['skuBundleId']def populateNegativeDeals():negativeDeals = get_mongo_connection(host=options.mongoHost).Catalog.NegativeDeals.find().distinct('sku')mc.set("negative_deals", negativeDeals, 600)def recomputeDeal(item):"""Lets recompute deal for this bundle"""print "Recomputing for bundleId %d" %(item.get('skuBundleId'))skuBundleId = item['skuBundleId']similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('netPriceAfterCashBack',pymongo.ASCENDING)]))bestPrice = float("inf")bestOne = NonebestSellerPoints = 0toUpdate = []prepaidBestPrice = float("inf")prepaidBestOne = NoneprepaidBestSellerPoints = 0for similarItem in similarItems:if similarItem['codAvailable'] ==1:if mc.get("negative_deals") is None:populateNegativeDeals()if similarItem['in_stock'] == 0 or similarItem['_id'] in mc.get("negative_deals"):get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})continueif similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})continueif similarItem.get('netPriceAfterCashBack') < bestPrice:bestOne = similarItembestPrice = similarItem.get('netPriceAfterCashBack')bestSellerPoints = similarItem['bestSellerPoints']elif similarItem.get('netPriceAfterCashBack') == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:bestOne = similarItembestPrice = similarItem.get('netPriceAfterCashBack')bestSellerPoints = similarItem['bestSellerPoints']else:passelse:if mc.get("negative_deals") is None:populateNegativeDeals()if similarItem['in_stock'] == 0 or similarItem['_id'] in mc.get("negative_deals"):get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})continueif similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})continueif similarItem.get('netPriceAfterCashBack') < prepaidBestPrice:prepaidBestOne = similarItemprepaidBestPrice = similarItem.get('netPriceAfterCashBack')prepaidBestSellerPoints = similarItem['bestSellerPoints']elif similarItem.get('netPriceAfterCashBack') == prepaidBestPrice and prepaidBestSellerPoints < similarItem['bestSellerPoints']:prepaidBestOne = similarItemprepaidBestPrice = similarItem.get('netPriceAfterCashBack')prepaidBestSellerPoints = similarItem['bestSellerPoints']else:passif bestOne is not None or prepaidBestOne is not None:for similarItem in similarItems:toUpdate.append(similarItem['_id'])if bestOne is not None:toUpdate.remove(bestOne['_id'])get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})if prepaidBestOne is not None:if bestOne is not None:if prepaidBestOne.get('netPriceAfterCashBack') < bestOne.get('netPriceAfterCashBack'):toUpdate.remove(prepaidBestOne['_id'])get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})else:toUpdate.remove(prepaidBestOne['_id'])get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})if len(toUpdate) > 0:get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)def main():populate()if __name__=='__main__':main()