Subversion Repositories SmartDukaan

Rev

Rev 16085 | Rev 16087 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
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
16085 kshitij.so 14
import chardet
13828 kshitij.so 15
 
16
con = None
17
 
14254 kshitij.so 18
parser = optparse.OptionParser()
19
parser.add_option("-m", "--m", dest="mongoHost",
20
                      default="localhost",
21
                      type="string", help="The HOST where the mongo server is running",
22
                      metavar="mongo_host")
23
 
24
(options, args) = parser.parse_args()
25
 
14325 kshitij.so 26
mc = MemCache(options.mongoHost)
14254 kshitij.so 27
 
16019 kshitij.so 28
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4, 'SHOPCLUES.COM':5}
29
 
13828 kshitij.so 30
headers = { 
31
           'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
32
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
33
            'Accept-Language' : 'en-US,en;q=0.8',                     
34
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
35
        }
36
 
14254 kshitij.so 37
def get_mongo_connection(host=options.mongoHost, port=27017):
13828 kshitij.so 38
    global con
39
    if con is None:
40
        print "Establishing connection %s host and port %d" %(host,port)
41
        try:
42
            con = pymongo.MongoClient(host, port)
43
        except Exception, e:
44
            print e
45
            return None
46
    return con
47
 
14180 kshitij.so 48
def populate():
49
    toScrapMap = {}
14132 kshitij.so 50
    bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0}}))
51
    for bestSeller in bestSellers: 
52
        snapdealBestSellers = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':3}))
53
        for data in snapdealBestSellers:
14180 kshitij.so 54
            if not toScrapMap.has_key(data['_id']):
15270 kshitij.so 55
                data['dealFlag'] = 0
56
                data['dealType'] = 0
57
                data['dealPoints'] = 0
58
                data['manualDealThresholdPrice'] = None
14180 kshitij.so 59
                toScrapMap[data['_id']] = data
14252 kshitij.so 60
    dealFlagged = list(get_mongo_connection().Catalog.Deals.find({'source_id':3,'showDeal':1,'totalPoints':{'$gt':0}}))
61
    for deal in dealFlagged:
62
        if not toScrapMap.has_key(deal['_id']):
14261 kshitij.so 63
            data = list(get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']}))
15270 kshitij.so 64
            data[0]['dealFlag'] = 0
65
            data[0]['dealType'] = 0
66
            data[0]['dealPoints'] = 0
67
            data[0]['manualDealThresholdPrice'] = None
14261 kshitij.so 68
            toScrapMap[deal['_id']] = data[0]
15270 kshitij.so 69
    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}))
70
    for manualDeal in manualDeals:
71
        if not toScrapMap.has_key(manualDeal['sku']):
72
            data = list(get_mongo_connection().Catalog.MasterData.find({'_id':manualDeal['sku']}))
73
            if len(data) > 0:
74
                data[0]['dealFlag'] = 1
75
                data[0]['dealType'] = manualDeal['dealType']
76
                data[0]['dealPoints'] = manualDeal['dealPoints']
77
                data[0]['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
78
                toScrapMap[manualDeal['sku']] = data[0]
79
        else:
80
            data = toScrapMap.get(manualDeal['sku'])
81
            data['dealFlag'] = 1
82
            data['dealType'] = manualDeal['dealType']
83
            data['dealPoints'] = manualDeal['dealPoints']
84
            data['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
16019 kshitij.so 85
    for val in toScrapMap.values():
86
        updatePrices(val)
87
#    pool = ThreadPool(cpu_count() *2)
88
#    offset = 0
89
#    limit =100
90
#    while(offset<=len(toScrapMap.values())):
91
#        pool.map(updatePrices,toScrapMap.values()[offset:offset+limit])
92
#        offset = offset + limit
93
#    pool.close()
94
#    pool.join()
95
#    print "joining threads at %s"%(str(datetime.now()))
14180 kshitij.so 96
 
97
 
98
def updatePrices(data):
99
    if data['source_id']!=3:
100
        return
101
    print data['identifier']
102
    if data['identifier'] is None or len(data['identifier'].strip())==0:
103
        print "returning"
104
        return
105
 
106
    try:
107
        if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):
108
            print "sku id is already updated",data['_id'] 
109
            return
110
    except:
111
        pass
112
 
15823 kshitij.so 113
    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 114
    print url
115
    lowestOfferPrice = 0
116
    instock = 0
15270 kshitij.so 117
    buyBoxPrice = 0
118
    isBuyBox = 1
119
    stock = 0
15820 kshitij.so 120
    try:
16019 kshitij.so 121
        req = urllib2.Request(url,headers=headers)
122
        response = urllib2.urlopen(req)
16085 kshitij.so 123
        snapdeal_data = response.read()
16019 kshitij.so 124
    except:
125
        print "Unable to scrape %d"%(data['_id'])
126
        return
16086 kshitij.so 127
    finally:
128
        response.close()
16085 kshitij.so 129
    encoding =  chardet.detect(snapdeal_data)
16019 kshitij.so 130
    try:
16085 kshitij.so 131
        snapdeal_data = snapdeal_data.decode(encoding.get('encoding'))
15820 kshitij.so 132
    except:
16085 kshitij.so 133
        snapdeal_data = snapdeal_data.decode(encoding.get('latin-1'))
134
    try:
135
        vendorInfo = json.loads(snapdeal_data)
136
    except:
16086 kshitij.so 137
        print "Unable to load json for %d"%(data['_id'])
15820 kshitij.so 138
        return
15270 kshitij.so 139
 
15820 kshitij.so 140
    try:
141
        buyBoxStock = vendorInfo['primaryVendor']['buyableInventory']
142
        if buyBoxStock >0:
143
            buyBoxPrice = vendorInfo['primaryVendor']['sellingPrice']
144
    except:
145
        pass
146
 
147
    sortedVendorsData = sorted(vendorInfo['vendors'], key=itemgetter('sellingPrice'))
148
    for sortedVendorData in sortedVendorsData:
149
        lowestOfferPrice = float(sortedVendorData['sellingPrice'])
150
        try:
151
            stock = sortedVendorData['buyableInventory']
152
        except:
153
            pass
154
        if stock > 0 and lowestOfferPrice > 0:
155
            instock = 1
156
            break
157
    if buyBoxPrice != lowestOfferPrice:
158
        isBuyBox = 0
159
 
14180 kshitij.so 160
    print lowestOfferPrice
161
    print instock
14181 kshitij.so 162
    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 163
    print "*************"
164
    if instock  == 1:
15270 kshitij.so 165
        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)
16019 kshitij.so 166
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':instock,'codAvailable':data['codAvailable']}}, multi=True)
14180 kshitij.so 167
    else:
15270 kshitij.so 168
        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)
16019 kshitij.so 169
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock,'codAvailable':data['codAvailable']}})
14180 kshitij.so 170
 
171
    try:
15270 kshitij.so 172
        recomputeDeal(data)
14180 kshitij.so 173
    except:
174
        print "Unable to compute deal for ",data['skuBundleId']
175
 
14325 kshitij.so 176
 
177
def populateNegativeDeals():
178
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
15270 kshitij.so 179
    mc.set("negative_deals", negativeDeals, 600)
180
 
181
def recomputePoints(item, deal):
182
    try:
183
        nlcPoints = getNlcPoints(item, deal['minNlc'], deal['maxNlc'], deal['available_price'])
184
    except:
185
        traceback.print_exc()
186
        nlcPoints = deal['nlcPoints']
187
    if item['manualDealThresholdPrice'] >= deal['available_price']:
188
        dealPoints = item['dealPoints']
189
    else:
190
        dealPoints = 0
191
    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']}})
192
 
14180 kshitij.so 193
 
15270 kshitij.so 194
def recomputeDeal(item):
13917 kshitij.so 195
    """Lets recompute deal for this bundle"""
16019 kshitij.so 196
    print "Recomputing for bundleId %d" %(item.get('skuBundleId'))
15270 kshitij.so 197
    skuBundleId = item['skuBundleId']
13917 kshitij.so 198
 
199
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
200
    bestPrice = float("inf")
201
    bestOne = None
202
    bestSellerPoints = 0
203
    toUpdate = []
16019 kshitij.so 204
    prepaidBestPrice = float("inf")
205
    prepaidBestOne = None
206
    prepaidBestSellerPoints = 0
13917 kshitij.so 207
    for similarItem in similarItems:
15270 kshitij.so 208
        if similarItem['_id'] == item['_id']:
209
            try:
210
                recomputePoints(item, similarItem)
211
            except:
212
                traceback.print_exc()
16019 kshitij.so 213
        if similarItem['codAvailable'] ==1:
214
            if mc.get("negative_deals") is None:
215
                populateNegativeDeals()
216
            if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
217
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
218
                continue
219
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
220
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
221
                continue
222
            if similarItem['available_price'] < bestPrice:
223
                bestOne = similarItem
224
                bestPrice = similarItem['available_price']
225
                bestSellerPoints = similarItem['bestSellerPoints']
226
            elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
227
                bestOne = similarItem
228
                bestPrice = similarItem['available_price']
229
                bestSellerPoints = similarItem['bestSellerPoints']
230
            else:
231
                pass
13917 kshitij.so 232
        else:
16019 kshitij.so 233
            if mc.get("negative_deals") is None:
234
                populateNegativeDeals()
235
            if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
236
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
237
                continue
238
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
239
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
240
                continue
241
            if similarItem['available_price'] < prepaidBestPrice:
242
                prepaidBestOne = similarItem
243
                prepaidBestPrice = similarItem['available_price']
244
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
245
            elif similarItem['available_price'] == prepaidBestPrice and prepaidBestSellerPoints < similarItem['bestSellerPoints']:
246
                prepaidBestOne = similarItem
247
                prepaidBestPrice = similarItem['available_price']
248
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
249
            else:
250
                pass
16026 kshitij.so 251
    if bestOne is not None or prepaidBestOne is not None:
13917 kshitij.so 252
        for similarItem in similarItems:
253
            toUpdate.append(similarItem['_id'])
16026 kshitij.so 254
        if bestOne is not None:
255
            toUpdate.remove(bestOne['_id'])
256
            get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})
257
        if prepaidBestOne is not None:
16070 kshitij.so 258
            if bestOne is not None:
259
                if prepaidBestOne['available_price'] < bestOne['available_price']: 
260
                    toUpdate.remove(prepaidBestOne['_id'])
261
                    get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
262
            else:
263
                toUpdate.remove(prepaidBestOne['_id'])
264
                get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
13917 kshitij.so 265
    if len(toUpdate) > 0:
16019 kshitij.so 266
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)
16026 kshitij.so 267
 
13828 kshitij.so 268
def main():
14180 kshitij.so 269
    populate()
13828 kshitij.so 270
 
271
if __name__=='__main__':
272
    main()