Subversion Repositories SmartDukaan

Rev

Rev 16070 | Rev 16086 | 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
16085 kshitij.so 127
    encoding =  chardet.detect(snapdeal_data)
16019 kshitij.so 128
    try:
16085 kshitij.so 129
        snapdeal_data = snapdeal_data.decode(encoding.get('encoding'))
15820 kshitij.so 130
    except:
16085 kshitij.so 131
        snapdeal_data = snapdeal_data.decode(encoding.get('latin-1'))
132
    try:
133
        vendorInfo = json.loads(snapdeal_data)
134
    except:
15820 kshitij.so 135
        return
136
    finally:
137
        response.close()
15270 kshitij.so 138
 
15820 kshitij.so 139
    try:
140
        buyBoxStock = vendorInfo['primaryVendor']['buyableInventory']
141
        if buyBoxStock >0:
142
            buyBoxPrice = vendorInfo['primaryVendor']['sellingPrice']
143
    except:
144
        pass
145
 
146
    sortedVendorsData = sorted(vendorInfo['vendors'], key=itemgetter('sellingPrice'))
147
    for sortedVendorData in sortedVendorsData:
148
        lowestOfferPrice = float(sortedVendorData['sellingPrice'])
149
        try:
150
            stock = sortedVendorData['buyableInventory']
151
        except:
152
            pass
153
        if stock > 0 and lowestOfferPrice > 0:
154
            instock = 1
155
            break
156
    if buyBoxPrice != lowestOfferPrice:
157
        isBuyBox = 0
158
 
14180 kshitij.so 159
    print lowestOfferPrice
160
    print instock
14181 kshitij.so 161
    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 162
    print "*************"
163
    if instock  == 1:
15270 kshitij.so 164
        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 165
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':instock,'codAvailable':data['codAvailable']}}, multi=True)
14180 kshitij.so 166
    else:
15270 kshitij.so 167
        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 168
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock,'codAvailable':data['codAvailable']}})
14180 kshitij.so 169
 
170
    try:
15270 kshitij.so 171
        recomputeDeal(data)
14180 kshitij.so 172
    except:
173
        print "Unable to compute deal for ",data['skuBundleId']
174
 
14325 kshitij.so 175
 
176
def populateNegativeDeals():
177
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
15270 kshitij.so 178
    mc.set("negative_deals", negativeDeals, 600)
179
 
180
def recomputePoints(item, deal):
181
    try:
182
        nlcPoints = getNlcPoints(item, deal['minNlc'], deal['maxNlc'], deal['available_price'])
183
    except:
184
        traceback.print_exc()
185
        nlcPoints = deal['nlcPoints']
186
    if item['manualDealThresholdPrice'] >= deal['available_price']:
187
        dealPoints = item['dealPoints']
188
    else:
189
        dealPoints = 0
190
    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']}})
191
 
14180 kshitij.so 192
 
15270 kshitij.so 193
def recomputeDeal(item):
13917 kshitij.so 194
    """Lets recompute deal for this bundle"""
16019 kshitij.so 195
    print "Recomputing for bundleId %d" %(item.get('skuBundleId'))
15270 kshitij.so 196
    skuBundleId = item['skuBundleId']
13917 kshitij.so 197
 
198
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
199
    bestPrice = float("inf")
200
    bestOne = None
201
    bestSellerPoints = 0
202
    toUpdate = []
16019 kshitij.so 203
    prepaidBestPrice = float("inf")
204
    prepaidBestOne = None
205
    prepaidBestSellerPoints = 0
13917 kshitij.so 206
    for similarItem in similarItems:
15270 kshitij.so 207
        if similarItem['_id'] == item['_id']:
208
            try:
209
                recomputePoints(item, similarItem)
210
            except:
211
                traceback.print_exc()
16019 kshitij.so 212
        if similarItem['codAvailable'] ==1:
213
            if mc.get("negative_deals") is None:
214
                populateNegativeDeals()
215
            if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
216
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
217
                continue
218
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
219
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
220
                continue
221
            if similarItem['available_price'] < bestPrice:
222
                bestOne = similarItem
223
                bestPrice = similarItem['available_price']
224
                bestSellerPoints = similarItem['bestSellerPoints']
225
            elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
226
                bestOne = similarItem
227
                bestPrice = similarItem['available_price']
228
                bestSellerPoints = similarItem['bestSellerPoints']
229
            else:
230
                pass
13917 kshitij.so 231
        else:
16019 kshitij.so 232
            if mc.get("negative_deals") is None:
233
                populateNegativeDeals()
234
            if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
235
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
236
                continue
237
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
238
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
239
                continue
240
            if similarItem['available_price'] < prepaidBestPrice:
241
                prepaidBestOne = similarItem
242
                prepaidBestPrice = similarItem['available_price']
243
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
244
            elif similarItem['available_price'] == prepaidBestPrice and prepaidBestSellerPoints < similarItem['bestSellerPoints']:
245
                prepaidBestOne = similarItem
246
                prepaidBestPrice = similarItem['available_price']
247
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
248
            else:
249
                pass
16026 kshitij.so 250
    if bestOne is not None or prepaidBestOne is not None:
13917 kshitij.so 251
        for similarItem in similarItems:
252
            toUpdate.append(similarItem['_id'])
16026 kshitij.so 253
        if bestOne is not None:
254
            toUpdate.remove(bestOne['_id'])
255
            get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})
256
        if prepaidBestOne is not None:
16070 kshitij.so 257
            if bestOne is not None:
258
                if prepaidBestOne['available_price'] < bestOne['available_price']: 
259
                    toUpdate.remove(prepaidBestOne['_id'])
260
                    get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
261
            else:
262
                toUpdate.remove(prepaidBestOne['_id'])
263
                get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
13917 kshitij.so 264
    if len(toUpdate) > 0:
16019 kshitij.so 265
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)
16026 kshitij.so 266
 
13828 kshitij.so 267
def main():
14180 kshitij.so 268
    populate()
13828 kshitij.so 269
 
270
if __name__=='__main__':
271
    main()