Subversion Repositories SmartDukaan

Rev

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