Subversion Repositories SmartDukaan

Rev

Rev 14334 | Rev 14355 | 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
14309 kshitij.so 8
from dtr.utils import AmazonDealScraper
14121 kshitij.so 9
from dtr.utils import FlipkartScraper,NewFlipkartScraper
14324 kshitij.so 10
from dtr.storage.MemCache import MemCache
14334 kshitij.so 11
from functools import partial
12
import threading
13829 kshitij.so 13
 
14324 kshitij.so 14
mc = MemCache("127.0.0.1")
15
 
13829 kshitij.so 16
con = None
14205 kshitij.so 17
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4}
13829 kshitij.so 18
 
19
headers = { 
20
           'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
21
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
22
            'Accept-Language' : 'en-US,en;q=0.8',                     
23
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
24
        }
25
 
26
def get_mongo_connection(host='localhost', port=27017):
27
    global con
28
    if con is None:
29
        print "Establishing connection %s host and port %d" %(host,port)
30
        try:
31
            con = pymongo.MongoClient(host, port)
32
        except Exception, e:
33
            print e
34
            return None
35
    return con
36
 
37
def returnLatestPrice(data, source_id):
13918 kshitij.so 38
    now = datetime.now()
13829 kshitij.so 39
    if source_id == 1:
40
        try:
13918 kshitij.so 41
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 42
                return {}
13918 kshitij.so 43
 
44
            try:
14309 kshitij.so 45
                if data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=0)):
13918 kshitij.so 46
                    print "sku id is already updated",data['_id'] 
13920 kshitij.so 47
                    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 48
            except:
49
                pass
50
 
51
 
13829 kshitij.so 52
            url = "http://www.amazon.in/gp/offer-listing/%s/ref=olp_sort_ps"%(data['identifier'])
53
            lowestPrice = 0.0
14309 kshitij.so 54
            print data['dealFlag']
55
            print data['dealType']
56
            try:
57
                if data['dealFlag'] ==1 and data['dealType'] ==1:
58
                    print "Inside deal"
59
                    deal_url = "http://www.amazon.in/dp/%s"%(data['identifier'].strip())
60
                    print deal_url
61
                    dealScraperAmazon = AmazonDealScraper.AmazonScraper()
62
                    lowestPrice = dealScraperAmazon.read(deal_url)
63
                    print lowestPrice
64
                    if lowestPrice == 0:
65
                        raise
66
                else:    
67
                    scraperAmazon = AmazonScraper()
68
                    lowestPrice = scraperAmazon.read(url)
69
            except Exception as e:
70
                print e
71
                scraperAmazon = AmazonScraper()
72
                lowestPrice = scraperAmazon.read(url)
13929 kshitij.so 73
            print "LowestPrice ",lowestPrice
13829 kshitij.so 74
            inStock = 0
75
            if lowestPrice > 0:
76
                inStock = 1
77
            if lowestPrice > 0:
13971 kshitij.so 78
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestPrice,'updatedOn':to_java_date(now),'priceUpdatedOn':to_java_date(now),'in_stock':inStock}}, multi=True)
14309 kshitij.so 79
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestPrice , 'in_stock':inStock,'dealType':data['dealType']}}, multi=True)
13829 kshitij.so 80
            else:
13929 kshitij.so 81
                lowestPrice = data['available_price']
13977 kshitij.so 82
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(now),'in_stock':0,'priceUpdatedOn':to_java_date(now)}}, multi=True)
14309 kshitij.so 83
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0,'dealType':data['dealType']}}, multi=True)
13918 kshitij.so 84
 
14334 kshitij.so 85
            try:
86
                thread = threading.Thread(target=partial(recomputeDeal, data['skuBundleId']))
14342 kshitij.so 87
                thread.daemon = True
14334 kshitij.so 88
                thread.start()    
13918 kshitij.so 89
            except:
90
                print "Unable to compute deal for ",data['skuBundleId']
91
 
14342 kshitij.so 92
            print "Returning info"
13829 kshitij.so 93
            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']}
94
        except:
13920 kshitij.so 95
            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 96
 
14203 kshitij.so 97
    elif source_id ==4:
14207 kshitij.so 98
 
14203 kshitij.so 99
        try:
14212 kshitij.so 100
            if data['identifier'] is None or len(data['identifier'].strip())==0:
101
                return {}
102
 
103
            try:
104
                if data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
105
                    print "sku id is already updated",data['_id'] 
106
                    return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':4,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
107
            except:
108
                pass
109
 
110
            url = "http://109.74.200.220:8080/mobileapi/dtr-pricing?id=%s"%(data['identifier'])
111
            lowestPrice = 0.0
112
            instock = 0
113
            req = urllib2.Request(url,headers=headers)
114
            response = urllib2.urlopen(req)
115
            json_input = response.read()
116
            response.close()
117
            priceInfo = json.loads(json_input)
118
            lowestPrice = priceInfo['response']['sellingPrice']
119
            if lowestPrice > 0:
120
                instock = 1
121
            if instock  == 1:
122
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestPrice,'updatedOn':to_java_date(now),'priceUpdatedOn':to_java_date(now),'in_stock':instock}}, multi=True)
123
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestPrice , 'in_stock':instock}}, multi=True)
124
            else:
125
                lowestPrice = data['available_price']
126
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(now),'in_stock':instock,'priceUpdatedOn':to_java_date(now)}}, multi=True)
127
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock}}, multi=True)
128
 
14334 kshitij.so 129
            try:
130
                thread = threading.Thread(target=partial(recomputeDeal, data['skuBundleId']))
14342 kshitij.so 131
                thread.daemon = True
14334 kshitij.so 132
                thread.start()
14212 kshitij.so 133
            except:
134
                print "Unable to compute deal for ",data['skuBundleId']
14342 kshitij.so 135
 
136
            print "Returning info"    
14212 kshitij.so 137
            return {'_id':data['_id'],'available_price':lowestPrice,'in_stock':instock,'source_id':4,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
138
 
14207 kshitij.so 139
        except:
14212 kshitij.so 140
            return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':4,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail']}
14203 kshitij.so 141
 
14207 kshitij.so 142
 
13829 kshitij.so 143
    elif source_id ==3:
144
        try:
13918 kshitij.so 145
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 146
                return {}
13918 kshitij.so 147
 
148
            try:
13975 kshitij.so 149
                if data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
13920 kshitij.so 150
                    print "sku id is already updated",data['_id']
151
                    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 152
 
153
            except Exception as e:
13920 kshitij.so 154
                print "Exception snapdeal"
13919 kshitij.so 155
                print e
13918 kshitij.so 156
                pass
157
 
158
 
13829 kshitij.so 159
            url="http://www.snapdeal.com/acors/json/gvbps?supc=%s&catId=175&sort=sellingPrice"%(data['identifier'])
160
            req = urllib2.Request(url,headers=headers)
161
            response = urllib2.urlopen(req)
14210 kshitij.so 162
            json_input = response.read()
14188 kshitij.so 163
            response.close()
13829 kshitij.so 164
            vendorInfo = json.loads(json_input)
165
            lowestOfferPrice = 0
166
            inStock = 0
167
            for vendor in vendorInfo:
168
                lowestOfferPrice = float(vendor['sellingPrice'])
169
                stock = vendor['buyableInventory']
170
                if stock > 0 and lowestOfferPrice > 0:
171
                    inStock = 1
172
                    break
173
 
174
            print lowestOfferPrice
175
            print inStock
176
            print "*************"
177
            if inStock  == 1:
13971 kshitij.so 178
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice,'updatedOn':to_java_date(now),'priceUpdatedOn':to_java_date(now),'in_stock':inStock}}, multi=True)
13918 kshitij.so 179
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':inStock}}, multi=True)
13829 kshitij.so 180
            else:
13929 kshitij.so 181
                lowestOfferPrice = data['available_price']
13977 kshitij.so 182
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(now),'in_stock':inStock,'priceUpdatedOn':to_java_date(now)}}, multi=True)
13918 kshitij.so 183
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock}}, multi=True)
184
 
14334 kshitij.so 185
            try:
186
                thread = threading.Thread(target=partial(recomputeDeal, data['skuBundleId']))
14342 kshitij.so 187
                thread.daemon = True
14334 kshitij.so 188
                thread.start()    
13918 kshitij.so 189
            except:
190
                print "Unable to compute deal for ",data['skuBundleId']
14342 kshitij.so 191
 
192
            print "Returning info"
13829 kshitij.so 193
            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']}
194
        except:
13920 kshitij.so 195
            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 196
 
197
    elif source_id == 2:
198
        try:
13918 kshitij.so 199
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 200
                return {}
13918 kshitij.so 201
 
202
            try:
13975 kshitij.so 203
                if data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
13918 kshitij.so 204
                    print "sku id is already updated",data['_id']
13920 kshitij.so 205
                    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 206
            except:
207
                pass
208
 
209
            lowestSp = 0
210
            inStock = 0
14189 kshitij.so 211
            scraperProductPage = NewFlipkartScraper.FlipkartProductPageScraper()
14121 kshitij.so 212
            try:
213
                if data['marketPlaceUrl']!="" or data['marketPlaceUrl'] !="http://www.flipkart.com/ps/%s"%(data['identifier']):
214
                    result = scraperProductPage.read(data['marketPlaceUrl'])
14124 kshitij.so 215
                    print result
14125 kshitij.so 216
                    if result.get('lowestSp')!=0:
217
                        lowestSp = result.get('lowestSp')
14121 kshitij.so 218
                        inStock = result.get('inStock')
219
            except:
220
                print "Unable to scrape product page ",data['identifier']
221
            if lowestSp ==0:
222
                url = "http://www.flipkart.com/ps/%s"%(data['identifier'])
14189 kshitij.so 223
                scraperFk = FlipkartScraper.FlipkartScraper()
14121 kshitij.so 224
                vendorsData = scraperFk.read(url)
225
                sortedVendorsData = []
226
                sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
227
                print "data",sortedVendorsData
228
                for vData in sortedVendorsData:
229
                    lowestSp = vData['sellingPrice']
230
                    break
231
                if lowestSp > 0:
232
                    inStock = 1
13829 kshitij.so 233
            print lowestSp
234
            print inStock
235
            if lowestSp > 0:
13971 kshitij.so 236
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp,'updatedOn':to_java_date(now),'priceUpdatedOn':to_java_date(now),'in_stock':inStock}}, multi=True)
13918 kshitij.so 237
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp , 'in_stock':inStock}}, multi=True)
13829 kshitij.so 238
            else:
13929 kshitij.so 239
                lowestSp = data['available_price']
13977 kshitij.so 240
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(now),'in_stock':inStock,'priceUpdatedOn':to_java_date(now)}}, multi=True)
13918 kshitij.so 241
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock}}, multi=True)
242
 
243
 
14334 kshitij.so 244
            try:
245
                thread = threading.Thread(target=partial(recomputeDeal, data['skuBundleId']))
14342 kshitij.so 246
                thread.daemon = True
14334 kshitij.so 247
                thread.start()    
13918 kshitij.so 248
            except:
249
                print "Unable to compute deal for ",data['skuBundleId']
14342 kshitij.so 250
 
251
            print "returning"    
13829 kshitij.so 252
            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']}
14342 kshitij.so 253
 
13829 kshitij.so 254
        except:
13920 kshitij.so 255
            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 256
    else:
257
        return {}
13918 kshitij.so 258
 
14324 kshitij.so 259
 
260
def populateNegativeDeals():
261
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
262
    mc.set("negative_deals", negativeDeals, 600)
263
 
13918 kshitij.so 264
def recomputeDeal(skuBundleId):
265
    """Lets recompute deal for this bundle"""
266
    print "Recomputing for bundleId",skuBundleId
13829 kshitij.so 267
 
13918 kshitij.so 268
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
269
    bestPrice = float("inf")
270
    bestOne = None
271
    bestSellerPoints = 0
272
    toUpdate = []
273
    for similarItem in similarItems:
14332 kshitij.so 274
        if mc.get("negative_deals") is None:
14324 kshitij.so 275
            populateNegativeDeals()
14332 kshitij.so 276
        if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
13918 kshitij.so 277
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
278
            continue
279
        if similarItem['available_price'] < bestPrice:
280
            bestOne = similarItem
281
            bestPrice = similarItem['available_price']
282
            bestSellerPoints = similarItem['bestSellerPoints']
283
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
284
            bestOne = similarItem
285
            bestPrice = similarItem['available_price']
286
            bestSellerPoints = similarItem['bestSellerPoints']
287
        else:
288
            pass
289
    if bestOne is not None:
290
        for similarItem in similarItems:
291
            toUpdate.append(similarItem['_id'])
292
        toUpdate.remove(bestOne['_id'])
293
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
294
    if len(toUpdate) > 0:
295
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
14342 kshitij.so 296
 
297
    print "Done with recomputing"
13829 kshitij.so 298
 
299
def getLatestPrice(skuBundleId, source_id):
300
    temp = []
301
    itemIds = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId,'source_id' : source_id}))
302
    for item in itemIds:
14309 kshitij.so 303
        item['dealFlag'] = 0
304
        item['dealType'] = 0
305
        manualDeals = list(get_mongo_connection().Catalog.ManualDeals.find({'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())},'source_id':source_id, 'sku':item['_id']}))
306
        if len(manualDeals) > 0:
307
            item['dealFlag'] = 1
308
            item['dealType'] =manualDeals[0]['dealType'] 
13829 kshitij.so 309
        temp.append(returnLatestPrice(item, source_id))
310
    return temp
311
 
13864 kshitij.so 312
def getLatestPriceById(id):
313
    item = list(get_mongo_connection().Catalog.MasterData.find({'_id':id}))
14309 kshitij.so 314
    item[0]['dealFlag'] = 0
315
    item[0]['dealType'] = 0
316
    manualDeals = list(get_mongo_connection().Catalog.ManualDeals.find({'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())},'source_id':item[0]['source_id'], 'sku':item[0]['_id']}))
317
    if len(manualDeals) > 0:
318
        item[0]['dealFlag'] = 1
319
        item[0]['dealType'] =manualDeals[0]['dealType'] 
13866 kshitij.so 320
    return returnLatestPrice(item[0], item[0]['source_id'])
13829 kshitij.so 321
 
322
 
323
def main():
14309 kshitij.so 324
    print getLatestPriceById(22746)
13829 kshitij.so 325
 
326
if __name__=='__main__':
13971 kshitij.so 327
    main()
328
 
329
"""21.06$"""