Subversion Repositories SmartDukaan

Rev

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