Subversion Repositories SmartDukaan

Rev

Rev 14332 | Rev 14342 | 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']))
87
                thread.start()    
13918 kshitij.so 88
            except:
89
                print "Unable to compute deal for ",data['skuBundleId']
90
 
13829 kshitij.so 91
            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']}
92
        except:
13920 kshitij.so 93
            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 94
 
14203 kshitij.so 95
    elif source_id ==4:
14207 kshitij.so 96
 
14203 kshitij.so 97
        try:
14212 kshitij.so 98
            if data['identifier'] is None or len(data['identifier'].strip())==0:
99
                return {}
100
 
101
            try:
102
                if data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
103
                    print "sku id is already updated",data['_id'] 
104
                    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']}
105
            except:
106
                pass
107
 
108
            url = "http://109.74.200.220:8080/mobileapi/dtr-pricing?id=%s"%(data['identifier'])
109
            lowestPrice = 0.0
110
            instock = 0
111
            req = urllib2.Request(url,headers=headers)
112
            response = urllib2.urlopen(req)
113
            json_input = response.read()
114
            response.close()
115
            priceInfo = json.loads(json_input)
116
            lowestPrice = priceInfo['response']['sellingPrice']
117
            if lowestPrice > 0:
118
                instock = 1
119
            if instock  == 1:
120
                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)
121
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestPrice , 'in_stock':instock}}, multi=True)
122
            else:
123
                lowestPrice = data['available_price']
124
                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)
125
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock}}, multi=True)
126
 
14334 kshitij.so 127
            try:
128
                thread = threading.Thread(target=partial(recomputeDeal, data['skuBundleId']))
129
                thread.start()
14212 kshitij.so 130
            except:
131
                print "Unable to compute deal for ",data['skuBundleId']
132
 
133
            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']}
134
 
14207 kshitij.so 135
        except:
14212 kshitij.so 136
            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 137
 
14207 kshitij.so 138
 
13829 kshitij.so 139
    elif source_id ==3:
140
        try:
13918 kshitij.so 141
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 142
                return {}
13918 kshitij.so 143
 
144
            try:
13975 kshitij.so 145
                if data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
13920 kshitij.so 146
                    print "sku id is already updated",data['_id']
147
                    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 148
 
149
            except Exception as e:
13920 kshitij.so 150
                print "Exception snapdeal"
13919 kshitij.so 151
                print e
13918 kshitij.so 152
                pass
153
 
154
 
13829 kshitij.so 155
            url="http://www.snapdeal.com/acors/json/gvbps?supc=%s&catId=175&sort=sellingPrice"%(data['identifier'])
156
            req = urllib2.Request(url,headers=headers)
157
            response = urllib2.urlopen(req)
14210 kshitij.so 158
            json_input = response.read()
14188 kshitij.so 159
            response.close()
13829 kshitij.so 160
            vendorInfo = json.loads(json_input)
161
            lowestOfferPrice = 0
162
            inStock = 0
163
            for vendor in vendorInfo:
164
                lowestOfferPrice = float(vendor['sellingPrice'])
165
                stock = vendor['buyableInventory']
166
                if stock > 0 and lowestOfferPrice > 0:
167
                    inStock = 1
168
                    break
169
 
170
            print lowestOfferPrice
171
            print inStock
172
            print "*************"
173
            if inStock  == 1:
13971 kshitij.so 174
                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 175
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':inStock}}, multi=True)
13829 kshitij.so 176
            else:
13929 kshitij.so 177
                lowestOfferPrice = data['available_price']
13977 kshitij.so 178
                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 179
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock}}, multi=True)
180
 
14334 kshitij.so 181
            try:
182
                thread = threading.Thread(target=partial(recomputeDeal, data['skuBundleId']))
183
                thread.start()    
13918 kshitij.so 184
            except:
185
                print "Unable to compute deal for ",data['skuBundleId']
186
 
13829 kshitij.so 187
            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']}
188
        except:
13920 kshitij.so 189
            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 190
 
191
    elif source_id == 2:
192
        try:
13918 kshitij.so 193
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 194
                return {}
13918 kshitij.so 195
 
196
            try:
13975 kshitij.so 197
                if data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
13918 kshitij.so 198
                    print "sku id is already updated",data['_id']
13920 kshitij.so 199
                    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 200
            except:
201
                pass
202
 
203
            lowestSp = 0
204
            inStock = 0
14189 kshitij.so 205
            scraperProductPage = NewFlipkartScraper.FlipkartProductPageScraper()
14121 kshitij.so 206
            try:
207
                if data['marketPlaceUrl']!="" or data['marketPlaceUrl'] !="http://www.flipkart.com/ps/%s"%(data['identifier']):
208
                    result = scraperProductPage.read(data['marketPlaceUrl'])
14124 kshitij.so 209
                    print result
14125 kshitij.so 210
                    if result.get('lowestSp')!=0:
211
                        lowestSp = result.get('lowestSp')
14121 kshitij.so 212
                        inStock = result.get('inStock')
213
            except:
214
                print "Unable to scrape product page ",data['identifier']
215
            if lowestSp ==0:
216
                url = "http://www.flipkart.com/ps/%s"%(data['identifier'])
14189 kshitij.so 217
                scraperFk = FlipkartScraper.FlipkartScraper()
14121 kshitij.so 218
                vendorsData = scraperFk.read(url)
219
                sortedVendorsData = []
220
                sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
221
                print "data",sortedVendorsData
222
                for vData in sortedVendorsData:
223
                    lowestSp = vData['sellingPrice']
224
                    break
225
                if lowestSp > 0:
226
                    inStock = 1
13829 kshitij.so 227
            print lowestSp
228
            print inStock
229
            if lowestSp > 0:
13971 kshitij.so 230
                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 231
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp , 'in_stock':inStock}}, multi=True)
13829 kshitij.so 232
            else:
13929 kshitij.so 233
                lowestSp = data['available_price']
13977 kshitij.so 234
                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 235
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock}}, multi=True)
236
 
237
 
14334 kshitij.so 238
            try:
239
                thread = threading.Thread(target=partial(recomputeDeal, data['skuBundleId']))
240
                thread.start()    
13918 kshitij.so 241
            except:
242
                print "Unable to compute deal for ",data['skuBundleId']
243
 
13829 kshitij.so 244
            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']}
245
        except:
13920 kshitij.so 246
            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 247
    else:
248
        return {}
13918 kshitij.so 249
 
14324 kshitij.so 250
 
251
def populateNegativeDeals():
252
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
253
    mc.set("negative_deals", negativeDeals, 600)
254
 
13918 kshitij.so 255
def recomputeDeal(skuBundleId):
256
    """Lets recompute deal for this bundle"""
257
    print "Recomputing for bundleId",skuBundleId
13829 kshitij.so 258
 
13918 kshitij.so 259
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
260
    bestPrice = float("inf")
261
    bestOne = None
262
    bestSellerPoints = 0
263
    toUpdate = []
264
    for similarItem in similarItems:
14332 kshitij.so 265
        if mc.get("negative_deals") is None:
14324 kshitij.so 266
            populateNegativeDeals()
14332 kshitij.so 267
        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 268
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
269
            continue
270
        if similarItem['available_price'] < bestPrice:
271
            bestOne = similarItem
272
            bestPrice = similarItem['available_price']
273
            bestSellerPoints = similarItem['bestSellerPoints']
274
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
275
            bestOne = similarItem
276
            bestPrice = similarItem['available_price']
277
            bestSellerPoints = similarItem['bestSellerPoints']
278
        else:
279
            pass
280
    if bestOne is not None:
281
        for similarItem in similarItems:
282
            toUpdate.append(similarItem['_id'])
283
        toUpdate.remove(bestOne['_id'])
284
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
285
    if len(toUpdate) > 0:
286
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
13829 kshitij.so 287
 
288
def getLatestPrice(skuBundleId, source_id):
289
    temp = []
290
    itemIds = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId,'source_id' : source_id}))
291
    for item in itemIds:
14309 kshitij.so 292
        item['dealFlag'] = 0
293
        item['dealType'] = 0
294
        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']}))
295
        if len(manualDeals) > 0:
296
            item['dealFlag'] = 1
297
            item['dealType'] =manualDeals[0]['dealType'] 
13829 kshitij.so 298
        temp.append(returnLatestPrice(item, source_id))
299
    return temp
300
 
13864 kshitij.so 301
def getLatestPriceById(id):
302
    item = list(get_mongo_connection().Catalog.MasterData.find({'_id':id}))
14309 kshitij.so 303
    item[0]['dealFlag'] = 0
304
    item[0]['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':item[0]['source_id'], 'sku':item[0]['_id']}))
306
    if len(manualDeals) > 0:
307
        item[0]['dealFlag'] = 1
308
        item[0]['dealType'] =manualDeals[0]['dealType'] 
13866 kshitij.so 309
    return returnLatestPrice(item[0], item[0]['source_id'])
13829 kshitij.so 310
 
311
 
312
def main():
14309 kshitij.so 313
    print getLatestPriceById(22746)
13829 kshitij.so 314
 
315
if __name__=='__main__':
13971 kshitij.so 316
    main()
317
 
318
"""21.06$"""