Subversion Repositories SmartDukaan

Rev

Rev 17036 | Rev 17181 | 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
15951 kshitij.so 4
from dtr.utils.utils import to_java_date, getNlcPoints, transformUrl
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
16410 kshitij.so 9
from dtr.utils import FlipkartScraper,NewFlipkartScraper, ShopCluesScraper, \
17013 manish.sha 10
PaytmOfferScraper, PaytmScraper, HomeShop18Scraper
14324 kshitij.so 11
from dtr.storage.MemCache import MemCache
14334 kshitij.so 12
from functools import partial
13
import threading
14760 kshitij.so 14
from dtr.utils.utils import getCashBack
14794 kshitij.so 15
import traceback
15174 kshitij.so 16
from shop2020.config.client.ConfigClient import ConfigClient
16065 kshitij.so 17
import chardet
16415 kshitij.so 18
from dtr.CouponMaster import addToPaytmMaster
13829 kshitij.so 19
 
15174 kshitij.so 20
config_client = ConfigClient()
21
host_memCache = config_client.get_property('mem_cache_host_dtr')
22
host = config_client.get_property('mongo_dtr_host')
14324 kshitij.so 23
 
15174 kshitij.so 24
mc = MemCache(host_memCache)
25
 
26
 
15902 kshitij.so 27
con  = None
17043 kshitij.so 28
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4, 'SHOPCLUES.COM':5,'PAYTM.COM':6,'HOMESHOP18':7}
13829 kshitij.so 29
 
30
headers = { 
31
           'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
32
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
33
            'Accept-Language' : 'en-US,en;q=0.8',                     
34
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
35
        }
36
 
15608 kshitij.so 37
 
15174 kshitij.so 38
def get_mongo_connection(port=27017):
13829 kshitij.so 39
    global con
40
    if con is None:
41
        print "Establishing connection %s host and port %d" %(host,port)
42
        try:
43
            con = pymongo.MongoClient(host, port)
44
        except Exception, e:
45
            print e
46
            return None
47
    return con
48
 
14828 kshitij.so 49
def returnLatestPrice(data, source_id, ignoreLastUpdated = True):
13918 kshitij.so 50
    now = datetime.now()
13829 kshitij.so 51
    if source_id == 1:
52
        try:
13918 kshitij.so 53
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 54
                return {}
13918 kshitij.so 55
 
16500 kshitij.so 56
            if data.get('ignorePricing') ==1:
57
                if data['dealFlag'] ==1 and data['dealType'] ==1:
16510 kshitij.so 58
                    data['marketPlaceUrl'] = data['dealUrl'].strip()
16117 kshitij.so 59
                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'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
15615 kshitij.so 60
 
61
 
14577 kshitij.so 62
            if data['dealFlag'] ==1 and data['dealType'] ==1:
16510 kshitij.so 63
                data['marketPlaceUrl'] = data['dealUrl'].strip()
14577 kshitij.so 64
 
13918 kshitij.so 65
            try:
14828 kshitij.so 66
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
13918 kshitij.so 67
                    print "sku id is already updated",data['_id'] 
16117 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'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
13918 kshitij.so 69
            except:
70
                pass
71
 
72
 
15956 kshitij.so 73
            url = "http://www.amazon.in/gp/aw/ol/%s?o=New&op=1"%(data['identifier'])
13829 kshitij.so 74
            lowestPrice = 0.0
14309 kshitij.so 75
            try:
76
                if data['dealFlag'] ==1 and data['dealType'] ==1:
77
                    print "Inside deal"
16510 kshitij.so 78
                    deal_url = data['marketPlaceUrl']
14309 kshitij.so 79
                    print deal_url
15213 kshitij.so 80
                    dealScraperAmazon = AmazonDealScraper.AmazonScraper(True)
14309 kshitij.so 81
                    lowestPrice = dealScraperAmazon.read(deal_url)
82
                    print lowestPrice
83
                    if lowestPrice == 0:
84
                        raise
85
                else:    
15213 kshitij.so 86
                    scraperAmazon = AmazonScraper(True)
14309 kshitij.so 87
                    lowestPrice = scraperAmazon.read(url)
88
            except Exception as e:
89
                print e
15213 kshitij.so 90
                scraperAmazon = AmazonScraper(True)
14309 kshitij.so 91
                lowestPrice = scraperAmazon.read(url)
13929 kshitij.so 92
            print "LowestPrice ",lowestPrice
13829 kshitij.so 93
            inStock = 0
94
            if lowestPrice > 0:
95
                inStock = 1
96
            if lowestPrice > 0:
13971 kshitij.so 97
                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)
16024 kshitij.so 98
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestPrice , 'in_stock':inStock,'dealType':data['dealType'],'codAvailable':data['codAvailable']}}, multi=True)
13829 kshitij.so 99
            else:
13929 kshitij.so 100
                lowestPrice = data['available_price']
13977 kshitij.so 101
                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)
16024 kshitij.so 102
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0,'dealType':data['dealType'],'codAvailable':data['codAvailable']}}, multi=True)
13918 kshitij.so 103
 
16117 kshitij.so 104
            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'], 'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
14834 kshitij.so 105
        except Exception as e:
106
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
107
            print e
16117 kshitij.so 108
            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'], 'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
13829 kshitij.so 109
 
14203 kshitij.so 110
    elif source_id ==4:
14207 kshitij.so 111
 
14203 kshitij.so 112
        try:
14212 kshitij.so 113
            if data['identifier'] is None or len(data['identifier'].strip())==0:
114
                return {}
115
 
16500 kshitij.so 116
            if data.get('ignorePricing') ==1:
117
                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'], 'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
118
 
14212 kshitij.so 119
            try:
14828 kshitij.so 120
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
14212 kshitij.so 121
                    print "sku id is already updated",data['_id'] 
16117 kshitij.so 122
                    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'], 'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
14212 kshitij.so 123
            except:
124
                pass
125
 
14840 kshitij.so 126
            url = "http://50.116.3.101:8080/mobileapi/dtr-pricing?id=%s"%(data['identifier'])
14212 kshitij.so 127
            lowestPrice = 0.0
128
            instock = 0
129
            req = urllib2.Request(url,headers=headers)
130
            response = urllib2.urlopen(req)
131
            json_input = response.read()
132
            response.close()
133
            priceInfo = json.loads(json_input)
134
            lowestPrice = priceInfo['response']['sellingPrice']
135
            if lowestPrice > 0:
136
                instock = 1
137
            if instock  == 1:
138
                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)
16024 kshitij.so 139
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestPrice , 'in_stock':instock,'codAvailable':data['codAvailable']}}, multi=True)
14212 kshitij.so 140
            else:
141
                lowestPrice = data['available_price']
142
                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)
16024 kshitij.so 143
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock,'codAvailable':data['codAvailable']}}, multi=True)
14212 kshitij.so 144
 
16205 kshitij.so 145
            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'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'],'tagline': data['tagline'], 'offer': data['offer']}
14834 kshitij.so 146
 
147
        except Exception as e:
148
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
149
            print e
16205 kshitij.so 150
            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'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'],'tagline': data['tagline'], 'offer': data['offer']}
14203 kshitij.so 151
 
14207 kshitij.so 152
 
13829 kshitij.so 153
    elif source_id ==3:
154
        try:
13918 kshitij.so 155
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 156
                return {}
13918 kshitij.so 157
 
16500 kshitij.so 158
            if data.get('ignorePricing') ==1:
16206 kshitij.so 159
                print "Ignored items returning for %d"%(data['_id'])
16265 kshitij.so 160
                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'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
16206 kshitij.so 161
 
13918 kshitij.so 162
            try:
14828 kshitij.so 163
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
13920 kshitij.so 164
                    print "sku id is already updated",data['_id']
16205 kshitij.so 165
                    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'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'],'tagline': data['tagline'], 'offer': data['offer']}
13919 kshitij.so 166
 
167
            except Exception as e:
13920 kshitij.so 168
                print "Exception snapdeal"
13919 kshitij.so 169
                print e
13918 kshitij.so 170
 
15819 kshitij.so 171
            url="http://www.snapdeal.com/acors/json/v2/gvbps?supc=%s&catUrl=&bn=&catId=175&start=0&count=10000"%(data['identifier'])
13829 kshitij.so 172
            req = urllib2.Request(url,headers=headers)
173
            response = urllib2.urlopen(req)
16065 kshitij.so 174
            snapdeal_data = response.read()
175
            encoding =  chardet.detect(snapdeal_data)
176
            try:
177
                snapdeal_data = snapdeal_data.decode(encoding.get('encoding'))
178
            except:
179
                snapdeal_data = snapdeal_data.decode(encoding.get('latin-1'))
180
            vendorInfo = json.loads(snapdeal_data)
14188 kshitij.so 181
            response.close()
13829 kshitij.so 182
            lowestOfferPrice = 0
183
            inStock = 0
15253 kshitij.so 184
            buyBoxPrice = 0
185
            isBuyBox = 1
15819 kshitij.so 186
            try:
187
                buyBoxStock = vendorInfo['primaryVendor']['buyableInventory']
188
                if buyBoxStock >0:
189
                    buyBoxPrice = vendorInfo['primaryVendor']['sellingPrice']
190
            except:
191
                pass
16065 kshitij.so 192
            print "buy box stock ",buyBoxStock
193
            print "bux box price ",buyBoxPrice
15819 kshitij.so 194
            sortedVendorsData = sorted(vendorInfo['vendors'], key=itemgetter('sellingPrice'))
15253 kshitij.so 195
            for sortedVendorData in sortedVendorsData:
196
                lowestOfferPrice = float(sortedVendorData['sellingPrice'])
197
                try:
198
                    stock = sortedVendorData['buyableInventory']
199
                except:
200
                    stock = 0
13829 kshitij.so 201
                if stock > 0 and lowestOfferPrice > 0:
202
                    inStock = 1
203
                    break
204
 
205
            print lowestOfferPrice
206
            print inStock
207
            print "*************"
15253 kshitij.so 208
 
209
            if buyBoxPrice != lowestOfferPrice:
210
                isBuyBox = 0
211
 
13829 kshitij.so 212
            if inStock  == 1:
15253 kshitij.so 213
                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,'buyBoxFlag':isBuyBox}}, multi=True)
16024 kshitij.so 214
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
13829 kshitij.so 215
            else:
13929 kshitij.so 216
                lowestOfferPrice = data['available_price']
15253 kshitij.so 217
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(now),'in_stock':inStock,'priceUpdatedOn':to_java_date(now),'buyBoxFlag':isBuyBox}}, multi=True)
16024 kshitij.so 218
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
13918 kshitij.so 219
 
16117 kshitij.so 220
            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'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
14834 kshitij.so 221
        except Exception as e:
15266 kshitij.so 222
            print traceback.print_exc()
14834 kshitij.so 223
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
224
            print e
16117 kshitij.so 225
            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'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
13829 kshitij.so 226
 
227
    elif source_id == 2:
228
        try:
13918 kshitij.so 229
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 230
                return {}
13918 kshitij.so 231
 
16500 kshitij.so 232
            if data.get('ignorePricing') ==1:
15608 kshitij.so 233
                print "Ignored items returning for %d"%(data['_id'])
16117 kshitij.so 234
                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'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
15608 kshitij.so 235
 
13918 kshitij.so 236
            try:
14828 kshitij.so 237
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
13918 kshitij.so 238
                    print "sku id is already updated",data['_id']
16117 kshitij.so 239
                    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'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']} 
13918 kshitij.so 240
            except:
241
                pass
242
 
243
            lowestSp = 0
244
            inStock = 0
15253 kshitij.so 245
            buyBoxPrice = 0
246
            isBuyBox = 0
14189 kshitij.so 247
            scraperProductPage = NewFlipkartScraper.FlipkartProductPageScraper()
14121 kshitij.so 248
            try:
249
                if data['marketPlaceUrl']!="" or data['marketPlaceUrl'] !="http://www.flipkart.com/ps/%s"%(data['identifier']):
250
                    result = scraperProductPage.read(data['marketPlaceUrl'])
14124 kshitij.so 251
                    print result
14125 kshitij.so 252
                    if result.get('lowestSp')!=0:
253
                        lowestSp = result.get('lowestSp')
14121 kshitij.so 254
                        inStock = result.get('inStock')
15253 kshitij.so 255
                        buyBoxPrice = result.get('buyBoxPrice')
14121 kshitij.so 256
            except:
257
                print "Unable to scrape product page ",data['identifier']
258
            if lowestSp ==0:
259
                url = "http://www.flipkart.com/ps/%s"%(data['identifier'])
14189 kshitij.so 260
                scraperFk = FlipkartScraper.FlipkartScraper()
15253 kshitij.so 261
                vendorsData, buyBoxInfo = (scraperFk.read(url))
14121 kshitij.so 262
                sortedVendorsData = []
263
                sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
264
                print "data",sortedVendorsData
265
                for vData in sortedVendorsData:
266
                    lowestSp = vData['sellingPrice']
267
                    break
268
                if lowestSp > 0:
269
                    inStock = 1
15975 kshitij.so 270
                try:
271
                    buyBoxPrice = buyBoxInfo[0].get('sellingPrice')
272
                except:
273
                    buyBoxPrice = None
13829 kshitij.so 274
            print lowestSp
275
            print inStock
15253 kshitij.so 276
            if buyBoxPrice is not None and buyBoxPrice == lowestSp:
277
                isBuyBox = 1
13829 kshitij.so 278
            if lowestSp > 0:
15253 kshitij.so 279
                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,'buyBoxFlag':isBuyBox}}, multi=True)
16024 kshitij.so 280
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp , 'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
13829 kshitij.so 281
            else:
13929 kshitij.so 282
                lowestSp = data['available_price']
15253 kshitij.so 283
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(now),'in_stock':inStock,'priceUpdatedOn':to_java_date(now),'buyBoxFlag':isBuyBox}}, multi=True)
16024 kshitij.so 284
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
13918 kshitij.so 285
 
16117 kshitij.so 286
            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'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
14342 kshitij.so 287
 
14834 kshitij.so 288
        except Exception as e:
289
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
290
            print e
16117 kshitij.so 291
            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'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
15902 kshitij.so 292
 
293
    elif source_id == 5:
294
        try:
16500 kshitij.so 295
            if data.get('ignorePricing') ==1:
15902 kshitij.so 296
                print "Ignored items returning for %d"%(data['_id'])
16117 kshitij.so 297
                return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':5,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
15902 kshitij.so 298
 
299
            try:
300
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
301
                    print "sku id is already updated",data['_id'] 
16117 kshitij.so 302
                    return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':5,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
15902 kshitij.so 303
            except:
304
                pass
305
 
306
 
307
            url = data['marketPlaceUrl']
308
            lowestPrice = 0.0
309
            try:
310
                sc = ShopCluesScraper.ShopCluesScraper()
15951 kshitij.so 311
                url = transformUrl(url, 5)
15902 kshitij.so 312
                productInfo = sc.read(url)
313
            except Exception as e:
16177 kshitij.so 314
                traceback.print_exc()
16176 kshitij.so 315
                productInfo = {}
16022 kshitij.so 316
                productInfo['price'] = 0.0
317
                productInfo['inStock'] = 0
318
                productInfo['isCod'] = 0
16178 kshitij.so 319
                productInfo['coupon'] = ""
16022 kshitij.so 320
 
15902 kshitij.so 321
            print "LowestPrice ",productInfo['price']
322
            if productInfo['price'] > 0 and productInfo['inStock']==1:
323
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':productInfo['price'],'coupon':productInfo['coupon'],'codAvailable':productInfo['isCod'],'updatedOn':to_java_date(now),'priceUpdatedOn':to_java_date(now),'in_stock':productInfo['inStock']}})
16024 kshitij.so 324
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':productInfo['price'] , 'in_stock':productInfo['inStock'],'dealType':data['dealType'], 'rank':data['rank'],'codAvailable':productInfo['isCod']}})
15902 kshitij.so 325
            else:
326
                lowestPrice = data['available_price']
327
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(now),'in_stock':0,'priceUpdatedOn':to_java_date(now)}})
16024 kshitij.so 328
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0,'dealType':data['dealType'],'rank':data['rank'],'codAvailable':productInfo['isCod']}})
15902 kshitij.so 329
 
16117 kshitij.so 330
            return {'_id':data['_id'],'available_price':productInfo['price'],'in_stock':productInfo['inStock'],'source_id':5,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail'], 'coupon':productInfo['coupon'],'codAvailable':productInfo['isCod'], 'tagline': data['tagline'], 'offer': data['offer']}
15902 kshitij.so 331
        except Exception as e:
332
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
16177 kshitij.so 333
            traceback.print_exc()
16117 kshitij.so 334
            return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':5,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
16410 kshitij.so 335
 
336
    elif source_id == 6:
337
        try:
16500 kshitij.so 338
            if data.get('ignorePricing') ==1:
16410 kshitij.so 339
                print "Ignored items returning for %d"%(data['_id'])
16491 kshitij.so 340
                return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':6,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer'],'gross_price':data.get('gross_price')}
16410 kshitij.so 341
 
342
            try:
343
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
344
                    print "sku id is already updated",data['_id'] 
16491 kshitij.so 345
                    return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':6,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer'],'gross_price':data.get('gross_price')}
16410 kshitij.so 346
            except:
347
                pass
348
 
349
            paytmScraper = PaytmScraper.PaytmScraper()
350
            url = "https://catalog.paytm.com/v1/mobile/product/%s"%(data['identifier'].strip())
351
            try:
352
                result = paytmScraper.read(url)
353
                effective_price = result.get('offerPrice')
16462 kshitij.so 354
                gross_price = effective_price
16410 kshitij.so 355
                coupon = ""
356
                try:
357
                    offers = PaytmOfferScraper.fetchOffers(result['offerUrl'])
16415 kshitij.so 358
                    try:
359
                        addToPaytmMaster(offers.get('codes'))
360
                    except:
361
                        print "Error in adding coupon"
362
                        traceback.print_exc()
16410 kshitij.so 363
                    bestOffer = {}
364
                    for offer_data in offers.get('codes'):
16415 kshitij.so 365
                        if effective_price > offer_data.get('effective_price'):
16410 kshitij.so 366
                            effective_price = offer_data.get('effective_price')
367
                            bestOffer = offer_data
368
                            coupon = bestOffer.get('code')
369
                except:
370
                    pass
16469 kshitij.so 371
 
372
                """Temp fix"""
373
                if len(coupon) > 0:
374
                    result['codAvailable'] = 0
375
 
16410 kshitij.so 376
                available_price = effective_price 
377
                if result['inStock']:
378
                    inStock = 1
16462 kshitij.so 379
                    get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':available_price,'updatedOn':to_java_date(datetime.now()),'priceUpdatedOn':to_java_date(datetime.now()),'in_stock':1,'buyBoxFlag':1,'codAvailable':result.get('codAvailable'),'coupon':coupon,'gross_price':gross_price}})
380
                    get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':available_price , 'in_stock':1,'codAvailable':result.get('codAvailable'),'gross_price':gross_price}})
16410 kshitij.so 381
                else:
382
                    inStock = 0
16415 kshitij.so 383
                    get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(datetime.now()),'in_stock':0,'priceUpdatedOn':to_java_date(datetime.now()),'buyBoxFlag':1,'codAvailable':result.get('codAvailable'),'coupon':coupon}})
384
                    get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0,'codAvailable':result.get('codAvailable')}})
16410 kshitij.so 385
 
386
            except:
387
                inStock = 0
388
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(datetime.now()),'in_stock':0,'priceUpdatedOn':to_java_date(datetime.now()),'buyBoxFlag':1}})
389
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0}})
390
 
391
 
16462 kshitij.so 392
            return {'_id':data['_id'],'available_price':available_price,'in_stock':inStock,'source_id':6,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail'], 'coupon':coupon,'codAvailable':result['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer'],'gross_price':gross_price}
16410 kshitij.so 393
        except Exception as e:
394
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
395
            traceback.print_exc()
16462 kshitij.so 396
            return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':6,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer'],'gross_price':data.get('gross_price')}
17013 manish.sha 397
 
398
    elif source_id ==7:
399
        try:
400
            if data['identifier'] is None or len(data['identifier'].strip())==0:
401
                return {}
402
 
403
            if data.get('ignorePricing') ==1:
404
                print "Ignored items returning for %d"%(data['_id'])
405
                return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':7,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
406
 
407
            try:
408
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
409
                    print "sku id is already updated",data['_id']
410
                    return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':7,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'],'tagline': data['tagline'], 'offer': data['offer']}
411
 
412
            except Exception as e:
413
                print "Exception snapdeal"
414
                print e
415
 
416
            response = None
417
 
418
            try:
17043 kshitij.so 419
                scraper = HomeShop18Scraper.HomeShop18Scraper()
17013 manish.sha 420
                response = scraper.read('http://m.homeshop18.com/product.mobi?productId=%s'%(str(data['identifier'])))
421
            except Exception as e:
422
                print e
17043 kshitij.so 423
                scraper = HomeShop18Scraper.HomeShop18Scraper()
17013 manish.sha 424
                response = scraper.read('http://m.homeshop18.com/product.mobi?productId=%s'%(str(data['identifier'])))
425
 
426
            lowestOfferPrice = 0
427
            inStock = 0
428
 
429
            if response is not None:
17043 kshitij.so 430
                lowestOfferPrice = float(response['price']+response['shippingCharge'])
17013 manish.sha 431
                inStock = response['inStock']          
432
 
433
            print lowestOfferPrice
434
            print inStock
435
            print "*************"
436
 
17036 kshitij.so 437
            if lowestOfferPrice ==0:
438
                inStock = 0
17013 manish.sha 439
 
17036 kshitij.so 440
 
17013 manish.sha 441
            if inStock  == 1:
17036 kshitij.so 442
                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)
17013 manish.sha 443
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
444
            else:
445
                lowestOfferPrice = data['available_price']
17036 kshitij.so 446
                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)
17013 manish.sha 447
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
448
 
449
            return {'_id':data['_id'],'available_price':lowestOfferPrice,'in_stock':inStock,'source_id':7,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
450
        except Exception as e:
451
            print traceback.print_exc()
452
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
453
            print e
454
            return {'_id':data['_id'],'available_price':data['available_price'],'in_stock':data['in_stock'],'source_id':7,'source_product_name':data['source_product_name'],'marketPlaceUrl':data['marketPlaceUrl'],'thumbnail':data['thumbnail'],'coupon':data['coupon'], 'codAvailable':data['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer']}
15902 kshitij.so 455
 
13829 kshitij.so 456
    else:
457
        return {}
15902 kshitij.so 458
 
459
 
13918 kshitij.so 460
 
16498 kshitij.so 461
def recomputePoints(deal):
15253 kshitij.so 462
    try:
16498 kshitij.so 463
        nlcPoints = getNlcPoints(deal)
15253 kshitij.so 464
    except:
16498 kshitij.so 465
        traceback.print_exc()
15253 kshitij.so 466
        nlcPoints = deal['nlcPoints']
16498 kshitij.so 467
 
468
    bundleDealPoints = list(get_mongo_connection().Catalog.DealPoints.find({'skuBundleId':deal['skuBundleId'],'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())}}))
469
    if len(bundleDealPoints) > 0:
470
        manualDealThresholdPrice = bundleDealPoints[0]['dealThresholdPrice']
471
        dealPoints = bundleDealPoints[0]['dealPoints']
15253 kshitij.so 472
    else:
473
        dealPoints = 0
16498 kshitij.so 474
        manualDealThresholdPrice = None
16508 kshitij.so 475
 
476
    if deal['available_price'] > manualDealThresholdPrice:
477
        dealPoints = 0
478
 
16498 kshitij.so 479
 
480
    if dealPoints != deal['dealPoints'] or manualDealThresholdPrice != deal['manualDealThresholdPrice'] or nlcPoints != deal['nlcPoints']:
481
        get_mongo_connection().Catalog.Deals.update({'_id':deal['_id']},{"$set":{'totalPoints':deal['totalPoints'] - deal['nlcPoints'] + nlcPoints - deal['dealPoints'] +dealPoints , 'nlcPoints': nlcPoints, 'dealPoints': dealPoints, 'manualDealThresholdPrice': manualDealThresholdPrice}})
15253 kshitij.so 482
 
15266 kshitij.so 483
 
484
def populateNegativeDeals():
485
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
486
    mc.set("negative_deals", negativeDeals, 600)
487
 
488
def recomputeDeal(item):
16017 kshitij.so 489
 
13918 kshitij.so 490
    """Lets recompute deal for this bundle"""
15266 kshitij.so 491
    print "Recomputing for bundleId",item.get('skuBundleId')
492
    skuBundleId = item['skuBundleId']
13829 kshitij.so 493
 
13918 kshitij.so 494
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
495
    bestPrice = float("inf")
496
    bestOne = None
497
    bestSellerPoints = 0
498
    toUpdate = []
16017 kshitij.so 499
    prepaidBestPrice = float("inf")
500
    prepaidBestOne = None
501
    prepaidBestSellerPoints = 0
13918 kshitij.so 502
    for similarItem in similarItems:
16498 kshitij.so 503
        try:
504
            recomputePoints(similarItem)
505
        except:
506
            traceback.print_exc()
16017 kshitij.so 507
        if similarItem['codAvailable'] ==1:
508
            if mc.get("negative_deals") is None:
509
                populateNegativeDeals()
16172 kshitij.so 510
            if similarItem['in_stock'] == 0  or similarItem['_id'] in mc.get("negative_deals"):
16017 kshitij.so 511
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
512
                continue
513
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
514
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
515
                continue
516
            if similarItem['available_price'] < bestPrice:
517
                bestOne = similarItem
518
                bestPrice = similarItem['available_price']
519
                bestSellerPoints = similarItem['bestSellerPoints']
520
            elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
521
                bestOne = similarItem
522
                bestPrice = similarItem['available_price']
523
                bestSellerPoints = similarItem['bestSellerPoints']
524
            else:
525
                pass
13918 kshitij.so 526
        else:
16017 kshitij.so 527
            if mc.get("negative_deals") is None:
528
                populateNegativeDeals()
16172 kshitij.so 529
            if similarItem['in_stock'] == 0  or similarItem['_id'] in mc.get("negative_deals"):
16017 kshitij.so 530
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
531
                continue
532
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
533
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
534
                continue
16869 kshitij.so 535
            if similarItem['source_id'] == SOURCE_MAP.get('PAYTM.COM'):
536
                similarItem['available_price'] = similarItem['gross_price']
16017 kshitij.so 537
            if similarItem['available_price'] < prepaidBestPrice:
538
                prepaidBestOne = similarItem
539
                prepaidBestPrice = similarItem['available_price']
540
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
541
            elif similarItem['available_price'] == prepaidBestPrice and prepaidBestSellerPoints < similarItem['bestSellerPoints']:
542
                prepaidBestOne = similarItem
543
                prepaidBestPrice = similarItem['available_price']
544
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
545
            else:
546
                pass
16024 kshitij.so 547
    print "bestOne ", bestOne
548
    print "prepaid best one",  prepaidBestOne
549
    if bestOne is not None or prepaidBestOne is not None:
13918 kshitij.so 550
        for similarItem in similarItems:
551
            toUpdate.append(similarItem['_id'])
16023 kshitij.so 552
        if bestOne is not None:
553
            toUpdate.remove(bestOne['_id'])
554
            get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})
555
        if prepaidBestOne is not None:
16069 kshitij.so 556
            if bestOne is not None:
557
                if prepaidBestOne['available_price'] < bestOne['available_price']: 
558
                    toUpdate.remove(prepaidBestOne['_id'])
559
                    get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
16072 kshitij.so 560
            else:
561
                toUpdate.remove(prepaidBestOne['_id'])
562
                get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
13918 kshitij.so 563
    if len(toUpdate) > 0:
16017 kshitij.so 564
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)
565
 
14342 kshitij.so 566
    print "Done with recomputing"
13829 kshitij.so 567
 
568
def getLatestPrice(skuBundleId, source_id):
569
    temp = []
570
    itemIds = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId,'source_id' : source_id}))
16026 kshitij.so 571
    item = None
13829 kshitij.so 572
    for item in itemIds:
14309 kshitij.so 573
        item['dealFlag'] = 0
574
        item['dealType'] = 0
16510 kshitij.so 575
        item['dealUrl'] = ""
15912 kshitij.so 576
        if item['source_id'] ==5 and item['rank'] == 0:
577
            continue
15187 kshitij.so 578
        if item['source_id'] ==3:
579
            item['marketPlaceUrl'] = item['marketPlaceUrl']+'?supc='+item.get('identifier')
14309 kshitij.so 580
        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']}))
581
        if len(manualDeals) > 0:
582
            item['dealFlag'] = 1
14760 kshitij.so 583
            item['dealType'] =manualDeals[0]['dealType']
16510 kshitij.so 584
            item['dealUrl'] = manualDeals[0]['dealUrl']
14760 kshitij.so 585
        info = returnLatestPrice(item, source_id)
14794 kshitij.so 586
        print info
14760 kshitij.so 587
        try:
588
            cashBack = getCashBack(item['_id'], item['source_id'], item['category_id'], mc, 'localhost')
14794 kshitij.so 589
            print "CashBack is ",cashBack
14760 kshitij.so 590
            if not cashBack or cashBack.get('cash_back_status')!=1:
14801 kshitij.so 591
                info['cash_back_type'] = 0
592
                info['cash_back'] = 0
14760 kshitij.so 593
            else:
594
                if cashBack['cash_back_type'] in (1,2):
595
                    info['cash_back_type'] = cashBack['cash_back_type']
596
                    info['cash_back'] = float(cashBack['cash_back'])
597
                else:
14801 kshitij.so 598
                    info['cash_back_type'] = 0
599
                    info['cash_back'] = 0
14760 kshitij.so 600
        except Exception as cashBackEx:
14794 kshitij.so 601
            traceback.print_exc()
14760 kshitij.so 602
            print "Error calculating cashback."
603
            info['cash_back_type'] = 0
604
            info['cash_back'] = 0
14794 kshitij.so 605
        print "info is ",info
14760 kshitij.so 606
        temp.append(info)
16026 kshitij.so 607
    if item is not None:
608
        try:
609
            thread = threading.Thread(target=recomputeDeal, args = (item,))
610
            thread.daemon = True
611
            thread.start()    
612
        except:
613
            print traceback.print_exc()
614
            print "Unable to compute deal for ",skuBundleId
13829 kshitij.so 615
    return temp
616
 
13864 kshitij.so 617
def getLatestPriceById(id):
618
    item = list(get_mongo_connection().Catalog.MasterData.find({'_id':id}))
14309 kshitij.so 619
    item[0]['dealFlag'] = 0
620
    item[0]['dealType'] = 0
16510 kshitij.so 621
    item[0]['dealUrl'] = ""
622
 
14309 kshitij.so 623
    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']}))
624
    if len(manualDeals) > 0:
625
        item[0]['dealFlag'] = 1
15266 kshitij.so 626
        item[0]['dealType'] =manualDeals[0]['dealType']
16510 kshitij.so 627
        item[0]['dealUrl'] = manualDeals[0]['dealUrl']
14367 kshitij.so 628
 
14431 kshitij.so 629
    info = returnLatestPrice(item[0], item[0]['source_id'])
14794 kshitij.so 630
    print info
14367 kshitij.so 631
    try:
14794 kshitij.so 632
        cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'], mc, 'localhost')
633
        print "CashBack is ",cashBack
14760 kshitij.so 634
        if not cashBack or cashBack.get('cash_back_status')!=1:
14801 kshitij.so 635
            info['cash_back_type'] = 0
636
            info['cash_back'] = 0
14760 kshitij.so 637
        else:
638
            if cashBack['cash_back_type'] in (1,2):
639
                info['cash_back_type'] = cashBack['cash_back_type']
640
                info['cash_back'] = float(cashBack['cash_back'])
641
            else:
14801 kshitij.so 642
                info['cash_back_type'] = 0
643
                info['cash_back'] = 0
14760 kshitij.so 644
    except Exception as cashBackEx:
14794 kshitij.so 645
        traceback.print_exc()
14760 kshitij.so 646
        print cashBackEx
647
        print "Error calculating cashback."
648
        info['cash_back_type'] = 0
649
        info['cash_back'] = 0
650
    try:
15273 kshitij.so 651
        thread = threading.Thread(target=recomputeDeal, args = (item[0],))
14367 kshitij.so 652
        thread.daemon = True
653
        thread.start()    
654
    except:
655
        print "Unable to compute deal for ",item[0]['skuBundleId']
14431 kshitij.so 656
    return info
13829 kshitij.so 657
 
14828 kshitij.so 658
def updatePriceForNotificationBundles(skuBundleId):
15266 kshitij.so 659
    itemIds = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId,'priceUpdatedOn':{'$lte':to_java_date(datetime.now() - timedelta(minutes=2))},'source_id':{"$in":SOURCE_MAP.values()}}))
14828 kshitij.so 660
    for item in itemIds:
14833 kshitij.so 661
        print item['_id']
14828 kshitij.so 662
        item['dealFlag'] = 0
663
        item['dealType'] = 0
16510 kshitij.so 664
        item['dealUrl'] = ""
14828 kshitij.so 665
        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['source_id'], 'sku':item['_id']}))
666
        if len(manualDeals) > 0:
667
            item['dealFlag'] = 1
668
            item['dealType'] =manualDeals[0]['dealType']
16510 kshitij.so 669
            item['dealUrl'] = manualDeals[0]['dealUrl']
14828 kshitij.so 670
        info = returnLatestPrice(item, item['source_id'],False)
671
        print info
672
 
13829 kshitij.so 673
def main():
15956 kshitij.so 674
    print datetime.now()
17043 kshitij.so 675
    print "retuned %s"%(str(getLatestPrice(1428,7)))
15956 kshitij.so 676
    print datetime.now()
13829 kshitij.so 677
if __name__=='__main__':
13971 kshitij.so 678
    main()
679