Subversion Repositories SmartDukaan

Rev

Rev 13918 | Rev 13920 | 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'] 
43
                    return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['inStock'],'source_id':1,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
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:
68
            return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['inStock'],'source_id':1,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
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)):
13918 kshitij.so 77
                    print "sku id is already updated",data['_id'] 
78
                    return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['inStock'],'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:
81
                print e
13918 kshitij.so 82
                pass
83
 
84
 
13829 kshitij.so 85
            url="http://www.snapdeal.com/acors/json/gvbps?supc=%s&catId=175&sort=sellingPrice"%(data['identifier'])
86
            req = urllib2.Request(url,headers=headers)
87
            response = urllib2.urlopen(req)
88
            json_input = response.read()
89
            vendorInfo = json.loads(json_input)
90
            lowestOfferPrice = 0
91
            inStock = 0
92
            for vendor in vendorInfo:
93
                lowestOfferPrice = float(vendor['sellingPrice'])
94
                stock = vendor['buyableInventory']
95
                if stock > 0 and lowestOfferPrice > 0:
96
                    inStock = 1
97
                    break
98
 
99
            print lowestOfferPrice
100
            print inStock
101
            print "*************"
102
            if inStock  == 1:
13918 kshitij.so 103
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice,'updatedOn':to_java_date(now),'in_stock':inStock}}, multi=True)
104
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':inStock}}, multi=True)
13829 kshitij.so 105
            else:
13918 kshitij.so 106
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(now),'in_stock':inStock}}, multi=True)
107
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock}}, multi=True)
108
 
109
            try:    
110
                recomputeDeal(data['skuBundleId'])
111
            except:
112
                print "Unable to compute deal for ",data['skuBundleId']
113
 
13829 kshitij.so 114
            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']}
115
        except:
116
            return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['inStock'],'source_id':3,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
117
 
118
    elif source_id == 2:
119
        try:
13918 kshitij.so 120
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 121
                return {}
13918 kshitij.so 122
 
123
            try:
13919 kshitij.so 124
                if data['updatedOn'] > to_java_date(now - timedelta(minutes=5)):
13918 kshitij.so 125
                    print "sku id is already updated",data['_id']
126
                    return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['inStock'],'source_id':2,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']} 
127
            except:
128
                pass
129
 
130
 
13829 kshitij.so 131
            url = "http://www.flipkart.com/ps/%s"%(data['identifier'])
132
            vendorsData = scraperFk.read(url)
133
            sortedVendorsData = []
134
            sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
135
            print "data",sortedVendorsData
13918 kshitij.so 136
            lowestSp = 0
137
            inStock = 0
13829 kshitij.so 138
            for vData in sortedVendorsData:
13918 kshitij.so 139
                lowestSp = vData['sellingPrice']
13829 kshitij.so 140
                break
141
            if lowestSp > 0:
142
                inStock = 1
143
            print lowestSp
144
            print inStock
145
            if lowestSp > 0:
13918 kshitij.so 146
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp,'updatedOn':to_java_date(now),'in_stock':inStock}}, multi=True)
147
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp , 'in_stock':inStock}}, multi=True)
13829 kshitij.so 148
            else:
13918 kshitij.so 149
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(now),'in_stock':inStock}}, multi=True)
150
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock}}, multi=True)
151
 
152
 
153
            try:    
154
                recomputeDeal(data['skuBundleId'])
155
            except:
156
                print "Unable to compute deal for ",data['skuBundleId']
157
 
13829 kshitij.so 158
            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']}
159
        except:
160
            return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['inStock'],'source_id':2,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
161
    else:
162
        return {}
163
 
13918 kshitij.so 164
 
165
def recomputeDeal(skuBundleId):
166
    """Lets recompute deal for this bundle"""
167
    print "Recomputing for bundleId",skuBundleId
13829 kshitij.so 168
 
13918 kshitij.so 169
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
170
    bestPrice = float("inf")
171
    bestOne = None
172
    bestSellerPoints = 0
173
    toUpdate = []
174
    for similarItem in similarItems:
175
        if similarItem['in_stock'] == 0:
176
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
177
            continue
178
        if similarItem['available_price'] < bestPrice:
179
            bestOne = similarItem
180
            bestPrice = similarItem['available_price']
181
            bestSellerPoints = similarItem['bestSellerPoints']
182
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
183
            bestOne = similarItem
184
            bestPrice = similarItem['available_price']
185
            bestSellerPoints = similarItem['bestSellerPoints']
186
        else:
187
            pass
188
    if bestOne is not None:
189
        for similarItem in similarItems:
190
            toUpdate.append(similarItem['_id'])
191
        toUpdate.remove(bestOne['_id'])
192
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
193
    if len(toUpdate) > 0:
194
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
13829 kshitij.so 195
 
196
def getLatestPrice(skuBundleId, source_id):
197
    temp = []
198
    itemIds = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId,'source_id' : source_id}))
199
    for item in itemIds:
200
        temp.append(returnLatestPrice(item, source_id))
201
    return temp
202
 
13864 kshitij.so 203
def getLatestPriceById(id):
204
    item = list(get_mongo_connection().Catalog.MasterData.find({'_id':id}))
13866 kshitij.so 205
    return returnLatestPrice(item[0], item[0]['source_id'])
13829 kshitij.so 206
 
207
 
208
def main():
13866 kshitij.so 209
    print getLatestPriceById(7)
13829 kshitij.so 210
 
211
if __name__=='__main__':
212
    main()