Subversion Repositories SmartDukaan

Rev

Rev 17751 | Rev 18722 | 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
 
17456 kshitij.so 126
            url = "http://173.255.209.200: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)
17456 kshitij.so 134
            print "PriceInfo ",data['identifier']
135
            print priceInfo
14212 kshitij.so 136
            lowestPrice = priceInfo['response']['sellingPrice']
137
            if lowestPrice > 0:
138
                instock = 1
139
            if instock  == 1:
140
                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 141
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestPrice , 'in_stock':instock,'codAvailable':data['codAvailable']}}, multi=True)
14212 kshitij.so 142
            else:
143
                lowestPrice = data['available_price']
144
                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 145
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock,'codAvailable':data['codAvailable']}}, multi=True)
14212 kshitij.so 146
 
16205 kshitij.so 147
            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 148
 
149
        except Exception as e:
150
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
151
            print e
16205 kshitij.so 152
            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 153
 
14207 kshitij.so 154
 
13829 kshitij.so 155
    elif source_id ==3:
156
        try:
13918 kshitij.so 157
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 158
                return {}
13918 kshitij.so 159
 
16500 kshitij.so 160
            if data.get('ignorePricing') ==1:
16206 kshitij.so 161
                print "Ignored items returning for %d"%(data['_id'])
16265 kshitij.so 162
                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 163
 
13918 kshitij.so 164
            try:
14828 kshitij.so 165
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
13920 kshitij.so 166
                    print "sku id is already updated",data['_id']
16205 kshitij.so 167
                    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 168
 
169
            except Exception as e:
13920 kshitij.so 170
                print "Exception snapdeal"
13919 kshitij.so 171
                print e
13918 kshitij.so 172
 
17295 kshitij.so 173
            url="http://www.snapdeal.com/acors/json/v2/gvbps?supc=%s&catUrl=&bn=&catId=175&start=0&count=10000&scoreCategoryUrl=mobiles-mobile-phones&make2Order=false&auto=false&isO2OVendorRequired=true"%(data['identifier'])
13829 kshitij.so 174
            req = urllib2.Request(url,headers=headers)
175
            response = urllib2.urlopen(req)
16065 kshitij.so 176
            snapdeal_data = response.read()
177
            encoding =  chardet.detect(snapdeal_data)
178
            try:
179
                snapdeal_data = snapdeal_data.decode(encoding.get('encoding'))
180
            except:
181
                snapdeal_data = snapdeal_data.decode(encoding.get('latin-1'))
182
            vendorInfo = json.loads(snapdeal_data)
14188 kshitij.so 183
            response.close()
13829 kshitij.so 184
            lowestOfferPrice = 0
185
            inStock = 0
15253 kshitij.so 186
            buyBoxPrice = 0
187
            isBuyBox = 1
15819 kshitij.so 188
            try:
189
                buyBoxStock = vendorInfo['primaryVendor']['buyableInventory']
190
                if buyBoxStock >0:
191
                    buyBoxPrice = vendorInfo['primaryVendor']['sellingPrice']
192
            except:
193
                pass
16065 kshitij.so 194
            print "buy box stock ",buyBoxStock
195
            print "bux box price ",buyBoxPrice
15819 kshitij.so 196
            sortedVendorsData = sorted(vendorInfo['vendors'], key=itemgetter('sellingPrice'))
15253 kshitij.so 197
            for sortedVendorData in sortedVendorsData:
198
                lowestOfferPrice = float(sortedVendorData['sellingPrice'])
199
                try:
200
                    stock = sortedVendorData['buyableInventory']
201
                except:
202
                    stock = 0
13829 kshitij.so 203
                if stock > 0 and lowestOfferPrice > 0:
204
                    inStock = 1
205
                    break
206
 
207
            print lowestOfferPrice
208
            print inStock
209
            print "*************"
15253 kshitij.so 210
 
211
            if buyBoxPrice != lowestOfferPrice:
212
                isBuyBox = 0
213
 
13829 kshitij.so 214
            if inStock  == 1:
15253 kshitij.so 215
                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 216
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
13829 kshitij.so 217
            else:
13929 kshitij.so 218
                lowestOfferPrice = data['available_price']
15253 kshitij.so 219
                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 220
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
13918 kshitij.so 221
 
16117 kshitij.so 222
            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 223
        except Exception as e:
15266 kshitij.so 224
            print traceback.print_exc()
14834 kshitij.so 225
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
226
            print e
16117 kshitij.so 227
            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 228
 
229
    elif source_id == 2:
230
        try:
13918 kshitij.so 231
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 232
                return {}
13918 kshitij.so 233
 
16500 kshitij.so 234
            if data.get('ignorePricing') ==1:
15608 kshitij.so 235
                print "Ignored items returning for %d"%(data['_id'])
16117 kshitij.so 236
                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 237
 
13918 kshitij.so 238
            try:
14828 kshitij.so 239
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
13918 kshitij.so 240
                    print "sku id is already updated",data['_id']
16117 kshitij.so 241
                    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 242
            except:
243
                pass
244
 
245
            lowestSp = 0
246
            inStock = 0
15253 kshitij.so 247
            buyBoxPrice = 0
248
            isBuyBox = 0
14189 kshitij.so 249
            scraperProductPage = NewFlipkartScraper.FlipkartProductPageScraper()
14121 kshitij.so 250
            try:
17262 kshitij.so 251
                result = scraperProductPage.read(data['identifier'])
252
                print result
253
                if result.get('lowestSp')!=0:
254
                    lowestSp = result.get('lowestSp')
255
                    inStock = result.get('inStock')
256
                    buyBoxPrice = result.get('buyBoxPrice')
14121 kshitij.so 257
            except:
258
                print "Unable to scrape product page ",data['identifier']
13829 kshitij.so 259
            print lowestSp
260
            print inStock
15253 kshitij.so 261
            if buyBoxPrice is not None and buyBoxPrice == lowestSp:
262
                isBuyBox = 1
13829 kshitij.so 263
            if lowestSp > 0:
15253 kshitij.so 264
                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 265
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp , 'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
13829 kshitij.so 266
            else:
13929 kshitij.so 267
                lowestSp = data['available_price']
15253 kshitij.so 268
                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 269
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
13918 kshitij.so 270
 
16117 kshitij.so 271
            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 272
 
14834 kshitij.so 273
        except Exception as e:
274
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
275
            print e
16117 kshitij.so 276
            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 277
 
278
    elif source_id == 5:
279
        try:
16500 kshitij.so 280
            if data.get('ignorePricing') ==1:
15902 kshitij.so 281
                print "Ignored items returning for %d"%(data['_id'])
16117 kshitij.so 282
                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 283
 
284
            try:
285
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
286
                    print "sku id is already updated",data['_id'] 
16117 kshitij.so 287
                    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 288
            except:
289
                pass
290
 
291
 
292
            url = data['marketPlaceUrl']
293
            lowestPrice = 0.0
294
            try:
295
                sc = ShopCluesScraper.ShopCluesScraper()
15951 kshitij.so 296
                url = transformUrl(url, 5)
15902 kshitij.so 297
                productInfo = sc.read(url)
298
            except Exception as e:
16177 kshitij.so 299
                traceback.print_exc()
16176 kshitij.so 300
                productInfo = {}
16022 kshitij.so 301
                productInfo['price'] = 0.0
302
                productInfo['inStock'] = 0
303
                productInfo['isCod'] = 0
16178 kshitij.so 304
                productInfo['coupon'] = ""
16022 kshitij.so 305
 
15902 kshitij.so 306
            print "LowestPrice ",productInfo['price']
307
            if productInfo['price'] > 0 and productInfo['inStock']==1:
308
                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 309
                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 310
            else:
311
                lowestPrice = data['available_price']
312
                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 313
                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 314
 
16117 kshitij.so 315
            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 316
        except Exception as e:
317
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
16177 kshitij.so 318
            traceback.print_exc()
16117 kshitij.so 319
            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 320
 
321
    elif source_id == 6:
322
        try:
16500 kshitij.so 323
            if data.get('ignorePricing') ==1:
16410 kshitij.so 324
                print "Ignored items returning for %d"%(data['_id'])
16491 kshitij.so 325
                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 326
 
327
            try:
328
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
329
                    print "sku id is already updated",data['_id'] 
16491 kshitij.so 330
                    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 331
            except:
332
                pass
333
 
334
            paytmScraper = PaytmScraper.PaytmScraper()
335
            url = "https://catalog.paytm.com/v1/mobile/product/%s"%(data['identifier'].strip())
336
            try:
337
                result = paytmScraper.read(url)
18282 kshitij.so 338
                print result
16410 kshitij.so 339
                effective_price = result.get('offerPrice')
16462 kshitij.so 340
                gross_price = effective_price
18282 kshitij.so 341
                shareUrl = result.get('shareUrl')
342
                if shareUrl is None:
343
                    shareUrl = data['marketPlaceUrl']
16410 kshitij.so 344
                coupon = ""
345
                try:
346
                    offers = PaytmOfferScraper.fetchOffers(result['offerUrl'])
16415 kshitij.so 347
                    try:
348
                        addToPaytmMaster(offers.get('codes'))
349
                    except:
350
                        print "Error in adding coupon"
351
                        traceback.print_exc()
16410 kshitij.so 352
                    bestOffer = {}
353
                    for offer_data in offers.get('codes'):
16415 kshitij.so 354
                        if effective_price > offer_data.get('effective_price'):
16410 kshitij.so 355
                            effective_price = offer_data.get('effective_price')
356
                            bestOffer = offer_data
357
                            coupon = bestOffer.get('code')
358
                except:
359
                    pass
16469 kshitij.so 360
 
361
                """Temp fix"""
362
                if len(coupon) > 0:
363
                    result['codAvailable'] = 0
364
 
16410 kshitij.so 365
                available_price = effective_price 
366
                if result['inStock']:
367
                    inStock = 1
18282 kshitij.so 368
                    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,'marketPlaceUrl':shareUrl}})
16462 kshitij.so 369
                    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 370
                else:
371
                    inStock = 0
18282 kshitij.so 372
                    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,'marketPlaceUrl':shareUrl}})
16415 kshitij.so 373
                    get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0,'codAvailable':result.get('codAvailable')}})
16410 kshitij.so 374
 
375
            except:
376
                inStock = 0
377
                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}})
378
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0}})
379
 
380
 
18282 kshitij.so 381
            return {'_id':data['_id'],'available_price':available_price,'in_stock':inStock,'source_id':6,'source_product_name':data['source_product_name'],'marketPlaceUrl':shareUrl,'thumbnail':data['thumbnail'], 'coupon':coupon,'codAvailable':result['codAvailable'], 'tagline': data['tagline'], 'offer': data['offer'],'gross_price':gross_price}
16410 kshitij.so 382
        except Exception as e:
383
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
384
            traceback.print_exc()
16462 kshitij.so 385
            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 386
 
387
    elif source_id ==7:
388
        try:
389
            if data['identifier'] is None or len(data['identifier'].strip())==0:
390
                return {}
391
 
392
            if data.get('ignorePricing') ==1:
393
                print "Ignored items returning for %d"%(data['_id'])
394
                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']}
395
 
396
            try:
397
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
398
                    print "sku id is already updated",data['_id']
399
                    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']}
400
 
401
            except Exception as e:
402
                print "Exception snapdeal"
403
                print e
404
 
405
            response = None
406
 
407
            try:
17043 kshitij.so 408
                scraper = HomeShop18Scraper.HomeShop18Scraper()
17013 manish.sha 409
                response = scraper.read('http://m.homeshop18.com/product.mobi?productId=%s'%(str(data['identifier'])))
410
            except Exception as e:
411
                print e
17043 kshitij.so 412
                scraper = HomeShop18Scraper.HomeShop18Scraper()
17013 manish.sha 413
                response = scraper.read('http://m.homeshop18.com/product.mobi?productId=%s'%(str(data['identifier'])))
414
 
415
            lowestOfferPrice = 0
416
            inStock = 0
417
 
418
            if response is not None:
17043 kshitij.so 419
                lowestOfferPrice = float(response['price']+response['shippingCharge'])
17013 manish.sha 420
                inStock = response['inStock']          
421
 
422
            print lowestOfferPrice
423
            print inStock
424
            print "*************"
425
 
17036 kshitij.so 426
            if lowestOfferPrice ==0:
427
                inStock = 0
17013 manish.sha 428
 
17036 kshitij.so 429
 
17013 manish.sha 430
            if inStock  == 1:
17036 kshitij.so 431
                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 432
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
433
            else:
434
                lowestOfferPrice = data['available_price']
17036 kshitij.so 435
                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 436
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
437
 
438
            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']}
439
        except Exception as e:
440
            print traceback.print_exc()
441
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
442
            print e
443
            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 444
 
13829 kshitij.so 445
    else:
446
        return {}
15902 kshitij.so 447
 
448
 
13918 kshitij.so 449
 
16498 kshitij.so 450
def recomputePoints(deal):
15253 kshitij.so 451
    try:
16498 kshitij.so 452
        nlcPoints = getNlcPoints(deal)
15253 kshitij.so 453
    except:
16498 kshitij.so 454
        traceback.print_exc()
15253 kshitij.so 455
        nlcPoints = deal['nlcPoints']
16498 kshitij.so 456
 
457
    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())}}))
458
    if len(bundleDealPoints) > 0:
459
        manualDealThresholdPrice = bundleDealPoints[0]['dealThresholdPrice']
460
        dealPoints = bundleDealPoints[0]['dealPoints']
15253 kshitij.so 461
    else:
462
        dealPoints = 0
16498 kshitij.so 463
        manualDealThresholdPrice = None
16508 kshitij.so 464
 
465
    if deal['available_price'] > manualDealThresholdPrice:
466
        dealPoints = 0
467
 
16498 kshitij.so 468
 
469
    if dealPoints != deal['dealPoints'] or manualDealThresholdPrice != deal['manualDealThresholdPrice'] or nlcPoints != deal['nlcPoints']:
470
        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 471
 
15266 kshitij.so 472
 
473
def populateNegativeDeals():
474
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
475
    mc.set("negative_deals", negativeDeals, 600)
476
 
477
def recomputeDeal(item):
16017 kshitij.so 478
 
13918 kshitij.so 479
    """Lets recompute deal for this bundle"""
15266 kshitij.so 480
    print "Recomputing for bundleId",item.get('skuBundleId')
481
    skuBundleId = item['skuBundleId']
13829 kshitij.so 482
 
13918 kshitij.so 483
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
484
    bestPrice = float("inf")
485
    bestOne = None
486
    bestSellerPoints = 0
487
    toUpdate = []
16017 kshitij.so 488
    prepaidBestPrice = float("inf")
489
    prepaidBestOne = None
490
    prepaidBestSellerPoints = 0
13918 kshitij.so 491
    for similarItem in similarItems:
16498 kshitij.so 492
        try:
493
            recomputePoints(similarItem)
494
        except:
495
            traceback.print_exc()
16017 kshitij.so 496
        if similarItem['codAvailable'] ==1:
497
            if mc.get("negative_deals") is None:
498
                populateNegativeDeals()
16172 kshitij.so 499
            if similarItem['in_stock'] == 0  or similarItem['_id'] in mc.get("negative_deals"):
16017 kshitij.so 500
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
501
                continue
17674 kshitij.so 502
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0 and similarItem['category_id']!=6:
16017 kshitij.so 503
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
504
                continue
505
            if similarItem['available_price'] < bestPrice:
506
                bestOne = similarItem
507
                bestPrice = similarItem['available_price']
508
                bestSellerPoints = similarItem['bestSellerPoints']
509
            elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
510
                bestOne = similarItem
511
                bestPrice = similarItem['available_price']
512
                bestSellerPoints = similarItem['bestSellerPoints']
513
            else:
514
                pass
13918 kshitij.so 515
        else:
16017 kshitij.so 516
            if mc.get("negative_deals") is None:
517
                populateNegativeDeals()
16172 kshitij.so 518
            if similarItem['in_stock'] == 0  or similarItem['_id'] in mc.get("negative_deals"):
16017 kshitij.so 519
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
520
                continue
17751 kshitij.so 521
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0 and similarItem['category_id']!=6:
16017 kshitij.so 522
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
523
                continue
16869 kshitij.so 524
            if similarItem['source_id'] == SOURCE_MAP.get('PAYTM.COM'):
525
                similarItem['available_price'] = similarItem['gross_price']
16017 kshitij.so 526
            if similarItem['available_price'] < prepaidBestPrice:
527
                prepaidBestOne = similarItem
528
                prepaidBestPrice = similarItem['available_price']
529
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
530
            elif similarItem['available_price'] == prepaidBestPrice and prepaidBestSellerPoints < similarItem['bestSellerPoints']:
531
                prepaidBestOne = similarItem
532
                prepaidBestPrice = similarItem['available_price']
533
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
534
            else:
535
                pass
17456 kshitij.so 536
    #print "bestOne ", bestOne
537
    #print "prepaid best one",  prepaidBestOne
16024 kshitij.so 538
    if bestOne is not None or prepaidBestOne is not None:
13918 kshitij.so 539
        for similarItem in similarItems:
540
            toUpdate.append(similarItem['_id'])
16023 kshitij.so 541
        if bestOne is not None:
542
            toUpdate.remove(bestOne['_id'])
543
            get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})
544
        if prepaidBestOne is not None:
16069 kshitij.so 545
            if bestOne is not None:
546
                if prepaidBestOne['available_price'] < bestOne['available_price']: 
547
                    toUpdate.remove(prepaidBestOne['_id'])
548
                    get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
16072 kshitij.so 549
            else:
550
                toUpdate.remove(prepaidBestOne['_id'])
551
                get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
13918 kshitij.so 552
    if len(toUpdate) > 0:
16017 kshitij.so 553
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)
554
 
14342 kshitij.so 555
    print "Done with recomputing"
13829 kshitij.so 556
 
557
def getLatestPrice(skuBundleId, source_id):
558
    temp = []
559
    itemIds = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId,'source_id' : source_id}))
16026 kshitij.so 560
    item = None
13829 kshitij.so 561
    for item in itemIds:
14309 kshitij.so 562
        item['dealFlag'] = 0
563
        item['dealType'] = 0
16510 kshitij.so 564
        item['dealUrl'] = ""
17674 kshitij.so 565
        if item['source_id'] ==5 and item['rank'] == 0 and item['category_id']!=6:
15912 kshitij.so 566
            continue
15187 kshitij.so 567
        if item['source_id'] ==3:
568
            item['marketPlaceUrl'] = item['marketPlaceUrl']+'?supc='+item.get('identifier')
14309 kshitij.so 569
        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']}))
570
        if len(manualDeals) > 0:
571
            item['dealFlag'] = 1
14760 kshitij.so 572
            item['dealType'] =manualDeals[0]['dealType']
16510 kshitij.so 573
            item['dealUrl'] = manualDeals[0]['dealUrl']
14760 kshitij.so 574
        info = returnLatestPrice(item, source_id)
14794 kshitij.so 575
        print info
14760 kshitij.so 576
        try:
577
            cashBack = getCashBack(item['_id'], item['source_id'], item['category_id'], mc, 'localhost')
14794 kshitij.so 578
            print "CashBack is ",cashBack
14760 kshitij.so 579
            if not cashBack or cashBack.get('cash_back_status')!=1:
14801 kshitij.so 580
                info['cash_back_type'] = 0
581
                info['cash_back'] = 0
14760 kshitij.so 582
            else:
583
                if cashBack['cash_back_type'] in (1,2):
17181 kshitij.so 584
 
585
                    if cashBack.get('maxCashBack') is not None:
586
 
587
                        if cashBack.get('cash_back_type') ==1 and (float(cashBack.get('cash_back'))*info['available_price'])/100 > cashBack.get('maxCashBack'):
588
                            cashBack['cash_back_type'] = 2
589
                            cashBack['cash_back'] = cashBack['maxCashBack']
590
                        elif cashBack.get('cash_back_type') ==2 and cashBack.get('cash_back') > cashBack.get('maxCashBack'):
591
                            cashBack['cash_back'] = cashBack['maxCashBack']
592
                        else:
593
                            pass
594
 
595
 
596
 
14760 kshitij.so 597
                    info['cash_back_type'] = cashBack['cash_back_type']
598
                    info['cash_back'] = float(cashBack['cash_back'])
599
                else:
14801 kshitij.so 600
                    info['cash_back_type'] = 0
601
                    info['cash_back'] = 0
14760 kshitij.so 602
        except Exception as cashBackEx:
14794 kshitij.so 603
            traceback.print_exc()
14760 kshitij.so 604
            print "Error calculating cashback."
605
            info['cash_back_type'] = 0
606
            info['cash_back'] = 0
14794 kshitij.so 607
        print "info is ",info
14760 kshitij.so 608
        temp.append(info)
16026 kshitij.so 609
    if item is not None:
610
        try:
611
            thread = threading.Thread(target=recomputeDeal, args = (item,))
612
            thread.daemon = True
613
            thread.start()    
614
        except:
615
            print traceback.print_exc()
616
            print "Unable to compute deal for ",skuBundleId
13829 kshitij.so 617
    return temp
618
 
13864 kshitij.so 619
def getLatestPriceById(id):
620
    item = list(get_mongo_connection().Catalog.MasterData.find({'_id':id}))
14309 kshitij.so 621
    item[0]['dealFlag'] = 0
622
    item[0]['dealType'] = 0
16510 kshitij.so 623
    item[0]['dealUrl'] = ""
624
 
14309 kshitij.so 625
    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']}))
626
    if len(manualDeals) > 0:
627
        item[0]['dealFlag'] = 1
15266 kshitij.so 628
        item[0]['dealType'] =manualDeals[0]['dealType']
16510 kshitij.so 629
        item[0]['dealUrl'] = manualDeals[0]['dealUrl']
14367 kshitij.so 630
 
14431 kshitij.so 631
    info = returnLatestPrice(item[0], item[0]['source_id'])
14794 kshitij.so 632
    print info
14367 kshitij.so 633
    try:
14794 kshitij.so 634
        cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'], mc, 'localhost')
635
        print "CashBack is ",cashBack
14760 kshitij.so 636
        if not cashBack or cashBack.get('cash_back_status')!=1:
14801 kshitij.so 637
            info['cash_back_type'] = 0
638
            info['cash_back'] = 0
14760 kshitij.so 639
        else:
640
            if cashBack['cash_back_type'] in (1,2):
641
                info['cash_back_type'] = cashBack['cash_back_type']
642
                info['cash_back'] = float(cashBack['cash_back'])
643
            else:
14801 kshitij.so 644
                info['cash_back_type'] = 0
645
                info['cash_back'] = 0
14760 kshitij.so 646
    except Exception as cashBackEx:
14794 kshitij.so 647
        traceback.print_exc()
14760 kshitij.so 648
        print cashBackEx
649
        print "Error calculating cashback."
650
        info['cash_back_type'] = 0
651
        info['cash_back'] = 0
652
    try:
15273 kshitij.so 653
        thread = threading.Thread(target=recomputeDeal, args = (item[0],))
14367 kshitij.so 654
        thread.daemon = True
655
        thread.start()    
656
    except:
657
        print "Unable to compute deal for ",item[0]['skuBundleId']
14431 kshitij.so 658
    return info
13829 kshitij.so 659
 
14828 kshitij.so 660
def updatePriceForNotificationBundles(skuBundleId):
15266 kshitij.so 661
    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 662
    for item in itemIds:
14833 kshitij.so 663
        print item['_id']
14828 kshitij.so 664
        item['dealFlag'] = 0
665
        item['dealType'] = 0
16510 kshitij.so 666
        item['dealUrl'] = ""
14828 kshitij.so 667
        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']}))
668
        if len(manualDeals) > 0:
669
            item['dealFlag'] = 1
670
            item['dealType'] =manualDeals[0]['dealType']
16510 kshitij.so 671
            item['dealUrl'] = manualDeals[0]['dealUrl']
14828 kshitij.so 672
        info = returnLatestPrice(item, item['source_id'],False)
673
        print info
674
 
13829 kshitij.so 675
def main():
15956 kshitij.so 676
    print datetime.now()
18282 kshitij.so 677
    print "retuned %s"%(str(getLatestPriceById(277)))
15956 kshitij.so 678
    print datetime.now()
13829 kshitij.so 679
if __name__=='__main__':
13971 kshitij.so 680
    main()
681