Subversion Repositories SmartDukaan

Rev

Rev 15827 | Rev 16026 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 15827 Rev 16019
Line 22... Line 22...
22
 
22
 
23
(options, args) = parser.parse_args()
23
(options, args) = parser.parse_args()
24
 
24
 
25
mc = MemCache(options.mongoHost)
25
mc = MemCache(options.mongoHost)
26
 
26
 
-
 
27
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4, 'SHOPCLUES.COM':5}
-
 
28
 
27
headers = { 
29
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',
30
           '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',      
31
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
30
            'Accept-Language' : 'en-US,en;q=0.8',                     
32
            'Accept-Language' : 'en-US,en;q=0.8',                     
31
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
33
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
Line 77... Line 79...
77
            data = toScrapMap.get(manualDeal['sku'])
79
            data = toScrapMap.get(manualDeal['sku'])
78
            data['dealFlag'] = 1
80
            data['dealFlag'] = 1
79
            data['dealType'] = manualDeal['dealType']
81
            data['dealType'] = manualDeal['dealType']
80
            data['dealPoints'] = manualDeal['dealPoints']
82
            data['dealPoints'] = manualDeal['dealPoints']
81
            data['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
83
            data['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
-
 
84
    for val in toScrapMap.values():
-
 
85
        updatePrices(val)
82
    pool = ThreadPool(cpu_count() *2)
86
#    pool = ThreadPool(cpu_count() *2)
83
    offset = 0
87
#    offset = 0
84
    limit =100
88
#    limit =100
85
    while(offset<=len(toScrapMap.values())):
89
#    while(offset<=len(toScrapMap.values())):
86
        pool.map(updatePrices,toScrapMap.values()[offset:offset+limit])
90
#        pool.map(updatePrices,toScrapMap.values()[offset:offset+limit])
87
        offset = offset + limit
91
#        offset = offset + limit
88
    pool.close()
92
#    pool.close()
89
    pool.join()
93
#    pool.join()
90
    print "joining threads at %s"%(str(datetime.now()))
94
#    print "joining threads at %s"%(str(datetime.now()))
91
 
95
 
92
 
96
 
93
def updatePrices(data):
97
def updatePrices(data):
94
    if data['source_id']!=3:
98
    if data['source_id']!=3:
95
        return
99
        return
Line 105... Line 109...
105
    except:
109
    except:
106
        pass
110
        pass
107
    
111
    
108
    url="http://www.snapdeal.com/acors/json/v2/gvbps?supc=%s&catUrl=&bn=&catId=175&start=0&count=10000"%(data['identifier'].strip())
112
    url="http://www.snapdeal.com/acors/json/v2/gvbps?supc=%s&catUrl=&bn=&catId=175&start=0&count=10000"%(data['identifier'].strip())
109
    print url
113
    print url
110
    time.sleep(1)
-
 
111
    lowestOfferPrice = 0
114
    lowestOfferPrice = 0
112
    instock = 0
115
    instock = 0
113
    buyBoxPrice = 0
116
    buyBoxPrice = 0
114
    isBuyBox = 1
117
    isBuyBox = 1
115
    stock = 0
118
    stock = 0
-
 
119
    try:
116
    req = urllib2.Request(url,headers=headers)
120
        req = urllib2.Request(url,headers=headers)
117
    response = urllib2.urlopen(req)
121
        response = urllib2.urlopen(req)
-
 
122
    except:
-
 
123
        print "Unable to scrape %d"%(data['_id'])
-
 
124
        return
118
    try:
125
    try:
119
        vendorInfo = json.load(response)
126
        vendorInfo = json.load(response)
120
    except:
127
    except:
121
        return
128
        return
122
    finally:
129
    finally:
Line 146... Line 153...
146
    print instock
153
    print instock
147
    print "Lowest Offer Price for id %d is %d , stock is %d and stock count is %d" %(data['_id'],lowestOfferPrice,instock,stock)
154
    print "Lowest Offer Price for id %d is %d , stock is %d and stock count is %d" %(data['_id'],lowestOfferPrice,instock,stock)
148
    print "*************"
155
    print "*************"
149
    if instock  == 1:
156
    if instock  == 1:
150
        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)
157
        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)
151
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':instock}}, multi=True)
158
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':instock,'codAvailable':data['codAvailable']}}, multi=True)
152
    else:
159
    else:
153
        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)
160
        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)
154
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock}}, multi=True)
161
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock,'codAvailable':data['codAvailable']}})
155
    
162
    
156
    try:
163
    try:
157
        recomputeDeal(data)
164
        recomputeDeal(data)
158
    except:
165
    except:
159
        print "Unable to compute deal for ",data['skuBundleId']
166
        print "Unable to compute deal for ",data['skuBundleId']
Line 176... Line 183...
176
    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']}})
183
    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']}})
177
 
184
 
178
    
185
    
179
def recomputeDeal(item):
186
def recomputeDeal(item):
180
    """Lets recompute deal for this bundle"""
187
    """Lets recompute deal for this bundle"""
181
    print "Recomputing for bundleId",item.get('skuBundleId')
188
    print "Recomputing for bundleId %d" %(item.get('skuBundleId'))
182
    skuBundleId = item['skuBundleId']
189
    skuBundleId = item['skuBundleId']
183
    
190
    
184
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
191
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
185
    bestPrice = float("inf")
192
    bestPrice = float("inf")
186
    bestOne = None
193
    bestOne = None
187
    bestSellerPoints = 0
194
    bestSellerPoints = 0
188
    toUpdate = []
195
    toUpdate = []
-
 
196
    prepaidBestPrice = float("inf")
-
 
197
    prepaidBestOne = None
-
 
198
    prepaidBestSellerPoints = 0
189
    for similarItem in similarItems:
199
    for similarItem in similarItems:
190
        if mc.get("negative_deals") is None:
-
 
191
            populateNegativeDeals()
-
 
192
#        try:
-
 
193
#            cashBack = getCashBack(similarItem['_id'], similarItem['source_id'], similarItem['category_id'], mc, options.mongoHost)
-
 
194
#            if not cashBack or cashBack.get('cash_back_status')!=1:
-
 
195
#                pass
-
 
196
#            else:
-
 
197
#                if cashBack['cash_back_type'] ==1:
-
 
198
#                    similarItem['available_price'] = similarItem['available_price'] - similarItem['available_price'] * float(cashBack['cash_back'])/100
-
 
199
#                elif cashBack['cash_back_type'] ==2:
-
 
200
#                    similarItem['available_price'] = similarItem['available_price'] - float(cashBack['cash_back'])
-
 
201
#                else:
-
 
202
#                    pass
-
 
203
#        except Exception as cashBackEx:
-
 
204
#            print cashBackEx
-
 
205
#            print "Error calculating cashback."
-
 
206
        if similarItem['_id'] == item['_id']:
200
        if similarItem['_id'] == item['_id']:
207
            try:
201
            try:
208
                recomputePoints(item, similarItem)
202
                recomputePoints(item, similarItem)
209
            except:
203
            except:
210
                traceback.print_exc()
204
                traceback.print_exc()
-
 
205
        if similarItem['codAvailable'] ==1:
-
 
206
            if mc.get("negative_deals") is None:
-
 
207
                populateNegativeDeals()
211
        if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
208
            if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
-
 
209
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
-
 
210
                continue
-
 
211
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
212
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
212
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
213
            continue
213
                continue
214
        if similarItem['available_price'] < bestPrice:
214
            if similarItem['available_price'] < bestPrice:
215
            bestOne = similarItem
215
                bestOne = similarItem
216
            bestPrice = similarItem['available_price']
216
                bestPrice = similarItem['available_price']
217
            bestSellerPoints = similarItem['bestSellerPoints']
217
                bestSellerPoints = similarItem['bestSellerPoints']
218
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
218
            elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
219
            bestOne = similarItem
219
                bestOne = similarItem
220
            bestPrice = similarItem['available_price']
220
                bestPrice = similarItem['available_price']
221
            bestSellerPoints = similarItem['bestSellerPoints']
221
                bestSellerPoints = similarItem['bestSellerPoints']
-
 
222
            else:
-
 
223
                pass
222
        else:
224
        else:
-
 
225
            if mc.get("negative_deals") is None:
-
 
226
                populateNegativeDeals()
-
 
227
            if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
-
 
228
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
-
 
229
                continue
-
 
230
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
-
 
231
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
-
 
232
                continue
-
 
233
            if similarItem['available_price'] < prepaidBestPrice:
-
 
234
                prepaidBestOne = similarItem
-
 
235
                prepaidBestPrice = similarItem['available_price']
-
 
236
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
-
 
237
            elif similarItem['available_price'] == prepaidBestPrice and prepaidBestSellerPoints < similarItem['bestSellerPoints']:
-
 
238
                prepaidBestOne = similarItem
-
 
239
                prepaidBestPrice = similarItem['available_price']
-
 
240
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
-
 
241
            else:
223
            pass
242
                pass
224
    if bestOne is not None:
243
    if bestOne is not None and prepaidBestOne is not None:
225
        for similarItem in similarItems:
244
        for similarItem in similarItems:
226
            toUpdate.append(similarItem['_id'])
245
            toUpdate.append(similarItem['_id'])
227
        toUpdate.remove(bestOne['_id'])
246
        toUpdate.remove(bestOne['_id'])
-
 
247
        toUpdate.remove(prepaidBestOne['_id'])
228
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
248
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})
-
 
249
        get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
229
    if len(toUpdate) > 0:
250
    if len(toUpdate) > 0:
230
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
251
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)
231
        
252
 
232
def main():
253
def main():
233
    populate()
254
    populate()
234
 
255
 
235
if __name__=='__main__':
256
if __name__=='__main__':
236
    main()
257
    main()
237
258