Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
13829 kshitij.so 1
import urllib2
2
import simplejson as json
3
import pymongo
4
from dtr.utils.utils import to_java_date
13918 kshitij.so 5
from datetime import datetime, timedelta
13829 kshitij.so 6
from operator import itemgetter
7
from dtr.utils.AmazonPriceOnlyScraper import AmazonScraper
13830 kshitij.so 8
from dtr.utils import FlipkartScraper
13829 kshitij.so 9
 
10
con = None
11
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3}
12
scraperFk = FlipkartScraper.FlipkartScraper()
13
scraperAmazon = AmazonScraper()
14
 
15
headers = { 
16
           'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
17
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
18
            'Accept-Language' : 'en-US,en;q=0.8',                     
19
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
20
        }
21
 
22
def get_mongo_connection(host='localhost', port=27017):
23
    global con
24
    if con is None:
25
        print "Establishing connection %s host and port %d" %(host,port)
26
        try:
27
            con = pymongo.MongoClient(host, port)
28
        except Exception, e:
29
            print e
30
            return None
31
    return con
32
 
33
def returnLatestPrice(data, source_id):
13918 kshitij.so 34
    now = datetime.now()
13829 kshitij.so 35
    if source_id == 1:
36
        try:
13918 kshitij.so 37
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 38
                return {}
13918 kshitij.so 39
 
40
            try:
13919 kshitij.so 41
                if data['updatedOn'] > to_java_date(now - timedelta(minutes=5)):
13918 kshitij.so 42
                    print "sku id is already updated",data['_id'] 
13920 kshitij.so 43
                    return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':1,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
13918 kshitij.so 44
            except:
45
                pass
46
 
47
 
13829 kshitij.so 48
            url = "http://www.amazon.in/gp/offer-listing/%s/ref=olp_sort_ps"%(data['identifier'])
49
            lowestPrice = 0.0
50
            lowestPrice = scraperAmazon.read(url)
51
            inStock = 0
52
            if lowestPrice > 0:
53
                inStock = 1
54
            if lowestPrice > 0:
13918 kshitij.so 55
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestPrice,'updatedOn':to_java_date(now),'in_stock':inStock}}, multi=True)
56
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestPrice , 'in_stock':inStock}}, multi=True)
13829 kshitij.so 57
            else:
13918 kshitij.so 58
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(now),'in_stock':0}}, multi=True)
59
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0}}, multi=True)
60
 
61
            try:    
62
                recomputeDeal(data['skuBundleId'])
63
            except:
64
                print "Unable to compute deal for ",data['skuBundleId']
65
 
13829 kshitij.so 66
            return {'_id':data['_id'],'available_price':lowestPrice,'in_stock':inStock,'source_id':1,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
67
        except:
13920 kshitij.so 68
            return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':1,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
13829 kshitij.so 69
 
70
    elif source_id ==3:
71
        try:
13918 kshitij.so 72
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 73
                return {}
13918 kshitij.so 74
 
75
            try:
13919 kshitij.so 76
                if data['updatedOn'] > to_java_date(now - timedelta(minutes=5)):
13920 kshitij.so 77
                    print "sku id is already updated",data['_id']
78
                    return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':3,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
13919 kshitij.so 79
 
80
            except Exception as e:
13920 kshitij.so 81
                print "Exception snapdeal"
13919 kshitij.so 82
                print e
13918 kshitij.so 83
                pass
84
 
85
 
13829 kshitij.so 86
            url="http://www.snapdeal.com/acors/json/gvbps?supc=%s&catId=175&sort=sellingPrice"%(data['identifier'])
87
            req = urllib2.Request(url,headers=headers)
88
            response = urllib2.urlopen(req)
89
            json_input = response.read()
90
            vendorInfo = json.loads(json_input)
91
            lowestOfferPrice = 0
92
            inStock = 0
93
            for vendor in vendorInfo:
94
                lowestOfferPrice = float(vendor['sellingPrice'])
95
                stock = vendor['buyableInventory']
96
                if stock > 0 and lowestOfferPrice > 0:
97
                    inStock = 1
98
                    break
99
 
100
            print lowestOfferPrice
101
            print inStock
102
            print "*************"
103
            if inStock  == 1:
13918 kshitij.so 104
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice,'updatedOn':to_java_date(now),'in_stock':inStock}}, multi=True)
105
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':inStock}}, multi=True)
13829 kshitij.so 106
            else:
13918 kshitij.so 107
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(now),'in_stock':inStock}}, multi=True)
108
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock}}, multi=True)
109
 
110
            try:    
111
                recomputeDeal(data['skuBundleId'])
112
            except:
113
                print "Unable to compute deal for ",data['skuBundleId']
114
 
13829 kshitij.so 115
            return {'_id':data['_id'],'available_price':lowestOfferPrice,'in_stock':inStock,'source_id':3,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
116
        except:
13920 kshitij.so 117
            return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':3,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
13829 kshitij.so 118
 
119
    elif source_id == 2:
120
        try:
13918 kshitij.so 121
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 122
                return {}
13918 kshitij.so 123
 
124
            try:
13919 kshitij.so 125
                if data['updatedOn'] > to_java_date(now - timedelta(minutes=5)):
13918 kshitij.so 126
                    print "sku id is already updated",data['_id']
13920 kshitij.so 127
                    return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':2,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']} 
13918 kshitij.so 128
            except:
129
                pass
130
 
131
 
13829 kshitij.so 132
            url = "http://www.flipkart.com/ps/%s"%(data['identifier'])
133
            vendorsData = scraperFk.read(url)
134
            sortedVendorsData = []
135
            sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
136
            print "data",sortedVendorsData
13918 kshitij.so 137
            lowestSp = 0
138
            inStock = 0
13829 kshitij.so 139
            for vData in sortedVendorsData:
13918 kshitij.so 140
                lowestSp = vData['sellingPrice']
13829 kshitij.so 141
                break
142
            if lowestSp > 0:
143
                inStock = 1
144
            print lowestSp
145
            print inStock
146
            if lowestSp > 0:
13918 kshitij.so 147
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp,'updatedOn':to_java_date(now),'in_stock':inStock}}, multi=True)
148
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp , 'in_stock':inStock}}, multi=True)
13829 kshitij.so 149
            else:
13918 kshitij.so 150
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(now),'in_stock':inStock}}, multi=True)
151
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock}}, multi=True)
152
 
153
 
154
            try:    
155
                recomputeDeal(data['skuBundleId'])
156
            except:
157
                print "Unable to compute deal for ",data['skuBundleId']
158
 
13829 kshitij.so 159
            return {'_id':data['_id'],'available_price':lowestSp,'in_stock':inStock,'source_id':2,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
160
        except:
13920 kshitij.so 161
            return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':2,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
13829 kshitij.so 162
    else:
163
        return {}
164
 
13918 kshitij.so 165
 
166
def recomputeDeal(skuBundleId):
167
    """Lets recompute deal for this bundle"""
168
    print "Recomputing for bundleId",skuBundleId
13829 kshitij.so 169
 
13918 kshitij.so 170
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
171
    bestPrice = float("inf")
172
    bestOne = None
173
    bestSellerPoints = 0
174
    toUpdate = []
175
    for similarItem in similarItems:
176
        if similarItem['in_stock'] == 0:
177
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
178
            continue
179
        if similarItem['available_price'] < bestPrice:
180
            bestOne = similarItem
181
            bestPrice = similarItem['available_price']
182
            bestSellerPoints = similarItem['bestSellerPoints']
183
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
184
            bestOne = similarItem
185
            bestPrice = similarItem['available_price']
186
            bestSellerPoints = similarItem['bestSellerPoints']
187
        else:
188
            pass
189
    if bestOne is not None:
190
        for similarItem in similarItems:
191
            toUpdate.append(similarItem['_id'])
192
        toUpdate.remove(bestOne['_id'])
193
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
194
    if len(toUpdate) > 0:
195
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
13829 kshitij.so 196
 
197
def getLatestPrice(skuBundleId, source_id):
198
    temp = []
199
    itemIds = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId,'source_id' : source_id}))
200
    for item in itemIds:
201
        temp.append(returnLatestPrice(item, source_id))
202
    return temp
203
 
13864 kshitij.so 204
def getLatestPriceById(id):
205
    item = list(get_mongo_connection().Catalog.MasterData.find({'_id':id}))
13866 kshitij.so 206
    return returnLatestPrice(item[0], item[0]['source_id'])
13829 kshitij.so 207
 
208
 
209
def main():
13920 kshitij.so 210
    print getLatestPriceById(148)
13829 kshitij.so 211
 
212
if __name__=='__main__':
213
    main()