Subversion Repositories SmartDukaan

Rev

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