Subversion Repositories SmartDukaan

Rev

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