Subversion Repositories SmartDukaan

Rev

Rev 14261 | Rev 14330 | 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
4
from dtr.utils.utils import to_java_date
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
13828 kshitij.so 11
 
12
con = None
13
 
14254 kshitij.so 14
parser = optparse.OptionParser()
15
parser.add_option("-m", "--m", dest="mongoHost",
16
                      default="localhost",
17
                      type="string", help="The HOST where the mongo server is running",
18
                      metavar="mongo_host")
19
 
20
(options, args) = parser.parse_args()
21
 
14325 kshitij.so 22
mc = MemCache(options.mongoHost)
14254 kshitij.so 23
 
13828 kshitij.so 24
headers = { 
25
           'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
26
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
27
            'Accept-Language' : 'en-US,en;q=0.8',                     
28
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
29
        }
30
 
14254 kshitij.so 31
def get_mongo_connection(host=options.mongoHost, port=27017):
13828 kshitij.so 32
    global con
33
    if con is None:
34
        print "Establishing connection %s host and port %d" %(host,port)
35
        try:
36
            con = pymongo.MongoClient(host, port)
37
        except Exception, e:
38
            print e
39
            return None
40
    return con
41
 
14180 kshitij.so 42
def populate():
43
    toScrapMap = {}
14132 kshitij.so 44
    bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0}}))
45
    for bestSeller in bestSellers: 
46
        snapdealBestSellers = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':3}))
47
        for data in snapdealBestSellers:
14180 kshitij.so 48
            if not toScrapMap.has_key(data['_id']):
49
                toScrapMap[data['_id']] = data
14252 kshitij.so 50
    dealFlagged = list(get_mongo_connection().Catalog.Deals.find({'source_id':3,'showDeal':1,'totalPoints':{'$gt':0}}))
51
    for deal in dealFlagged:
52
        if not toScrapMap.has_key(deal['_id']):
14261 kshitij.so 53
            data = list(get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']}))
54
            toScrapMap[deal['_id']] = data[0]
14180 kshitij.so 55
    pool = ThreadPool(cpu_count() *2)
56
    pool.map(updatePrices,toScrapMap.values())
57
    pool.close()
58
    pool.join()
14252 kshitij.so 59
    print "joining threads at %s"%(str(datetime.now()))
14180 kshitij.so 60
 
61
 
62
def updatePrices(data):
63
    if data['source_id']!=3:
64
        return
65
    print data['identifier']
66
    if data['identifier'] is None or len(data['identifier'].strip())==0:
67
        print "returning"
68
        return
69
 
70
    try:
71
        if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):
72
            print "sku id is already updated",data['_id'] 
73
            return
74
    except:
75
        pass
76
 
77
    url="http://www.snapdeal.com/acors/json/gvbps?supc=%s&catId=175&sort=sellingPrice"%(data['identifier'].strip())
78
    print url
79
    time.sleep(1)
80
    lowestOfferPrice = 0
81
    instock = 0
82
    req = urllib2.Request(url,headers=headers)
83
    response = urllib2.urlopen(req)
14209 kshitij.so 84
    json_input = response.read()
14187 kshitij.so 85
    response.close()
14180 kshitij.so 86
    if len(json_input) > 0:
87
        vendorInfo = json.loads(json_input)
88
        for vendor in vendorInfo:
89
            lowestOfferPrice = float(vendor['sellingPrice'])
14181 kshitij.so 90
            try:
91
                stock = vendor['buyableInventory']
92
            except:
93
                stock = 0
14180 kshitij.so 94
            if stock > 0 and lowestOfferPrice > 0:
95
                instock = 1
96
                break
14181 kshitij.so 97
    else:
98
        lowestOfferPrice = 0
99
        stock = 0
100
        instock = 0
101
 
14180 kshitij.so 102
    print lowestOfferPrice
103
    print instock
104
    print stock
14181 kshitij.so 105
    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 106
    print "*************"
107
    if instock  == 1:
108
        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}}, multi=True)
109
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':instock}}, multi=True)
110
    else:
111
        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())}}, multi=True)
112
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock}}, multi=True)
113
 
114
    try:
115
        recomputeDeal(data['skuBundleId'])
116
    except:
117
        print "Unable to compute deal for ",data['skuBundleId']
118
 
14325 kshitij.so 119
 
120
def populateNegativeDeals():
121
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
122
    mc.set("negative_deals", negativeDeals, 600) 
14180 kshitij.so 123
 
13917 kshitij.so 124
def recomputeDeal(skuBundleId):
125
    """Lets recompute deal for this bundle"""
126
    print "Recomputing for bundleId",skuBundleId
127
 
128
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
129
    bestPrice = float("inf")
130
    bestOne = None
131
    bestSellerPoints = 0
132
    toUpdate = []
133
    for similarItem in similarItems:
14325 kshitij.so 134
        if mc.get("negativeDeals") is None:
135
            populateNegativeDeals()
136
        if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negativeDeals"):
13917 kshitij.so 137
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
138
            continue
139
        if similarItem['available_price'] < bestPrice:
140
            bestOne = similarItem
141
            bestPrice = similarItem['available_price']
142
            bestSellerPoints = similarItem['bestSellerPoints']
143
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
144
            bestOne = similarItem
145
            bestPrice = similarItem['available_price']
146
            bestSellerPoints = similarItem['bestSellerPoints']
147
        else:
148
            pass
149
    if bestOne is not None:
150
        for similarItem in similarItems:
151
            toUpdate.append(similarItem['_id'])
152
        toUpdate.remove(bestOne['_id'])
153
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
154
    if len(toUpdate) > 0:
155
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
156
 
13828 kshitij.so 157
def main():
14180 kshitij.so 158
    populate()
13828 kshitij.so 159
 
160
if __name__=='__main__':
161
    main()