Subversion Repositories SmartDukaan

Rev

Rev 16024 | Rev 16065 | 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
15902 kshitij.so 9
from dtr.utils import FlipkartScraper,NewFlipkartScraper, ShopCluesScraper
14324 kshitij.so 10
from dtr.storage.MemCache import MemCache
14334 kshitij.so 11
from functools import partial
12
import threading
14760 kshitij.so 13
from dtr.utils.utils import getCashBack
14794 kshitij.so 14
import traceback
15174 kshitij.so 15
from shop2020.config.client.ConfigClient import ConfigClient
13829 kshitij.so 16
 
15174 kshitij.so 17
config_client = ConfigClient()
18
host_memCache = config_client.get_property('mem_cache_host_dtr')
19
host = config_client.get_property('mongo_dtr_host')
14324 kshitij.so 20
 
15174 kshitij.so 21
mc = MemCache(host_memCache)
22
 
23
 
15902 kshitij.so 24
con  = None
25
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4, 'SHOPCLUES.COM':5}
13829 kshitij.so 26
 
27
headers = { 
28
           'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
29
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
30
            'Accept-Language' : 'en-US,en;q=0.8',                     
31
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
32
        }
33
 
15902 kshitij.so 34
ignoreItems = []
15608 kshitij.so 35
 
15174 kshitij.so 36
def get_mongo_connection(port=27017):
13829 kshitij.so 37
    global con
38
    if con is None:
39
        print "Establishing connection %s host and port %d" %(host,port)
40
        try:
41
            con = pymongo.MongoClient(host, port)
42
        except Exception, e:
43
            print e
44
            return None
45
    return con
46
 
14828 kshitij.so 47
def returnLatestPrice(data, source_id, ignoreLastUpdated = True):
13918 kshitij.so 48
    now = datetime.now()
13829 kshitij.so 49
    if source_id == 1:
50
        try:
13918 kshitij.so 51
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 52
                return {}
13918 kshitij.so 53
 
15615 kshitij.so 54
            if data['_id'] in ignoreItems:
55
                print "Ignored items returning for %d"%(data['_id'])
15913 kshitij.so 56
                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']}
15615 kshitij.so 57
 
58
 
14577 kshitij.so 59
            if data['dealFlag'] ==1 and data['dealType'] ==1:
60
                data['marketPlaceUrl'] = "http://www.amazon.in/dp/%s"%(data['identifier'].strip())
61
 
13918 kshitij.so 62
            try:
14828 kshitij.so 63
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
13918 kshitij.so 64
                    print "sku id is already updated",data['_id'] 
15913 kshitij.so 65
                    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']}
13918 kshitij.so 66
            except:
67
                pass
68
 
69
 
15956 kshitij.so 70
            url = "http://www.amazon.in/gp/aw/ol/%s?o=New&op=1"%(data['identifier'])
13829 kshitij.so 71
            lowestPrice = 0.0
14309 kshitij.so 72
            try:
73
                if data['dealFlag'] ==1 and data['dealType'] ==1:
74
                    print "Inside deal"
75
                    deal_url = "http://www.amazon.in/dp/%s"%(data['identifier'].strip())
76
                    print deal_url
15213 kshitij.so 77
                    dealScraperAmazon = AmazonDealScraper.AmazonScraper(True)
14309 kshitij.so 78
                    lowestPrice = dealScraperAmazon.read(deal_url)
79
                    print lowestPrice
80
                    if lowestPrice == 0:
81
                        raise
82
                else:    
15213 kshitij.so 83
                    scraperAmazon = AmazonScraper(True)
14309 kshitij.so 84
                    lowestPrice = scraperAmazon.read(url)
85
            except Exception as e:
86
                print e
15213 kshitij.so 87
                scraperAmazon = AmazonScraper(True)
14309 kshitij.so 88
                lowestPrice = scraperAmazon.read(url)
13929 kshitij.so 89
            print "LowestPrice ",lowestPrice
13829 kshitij.so 90
            inStock = 0
91
            if lowestPrice > 0:
92
                inStock = 1
93
            if lowestPrice > 0:
13971 kshitij.so 94
                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 95
                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 96
            else:
13929 kshitij.so 97
                lowestPrice = data['available_price']
13977 kshitij.so 98
                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 99
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0,'dealType':data['dealType'],'codAvailable':data['codAvailable']}}, multi=True)
13918 kshitij.so 100
 
15913 kshitij.so 101
            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']}
14834 kshitij.so 102
        except Exception as e:
103
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
104
            print e
15913 kshitij.so 105
            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']}
13829 kshitij.so 106
 
14203 kshitij.so 107
    elif source_id ==4:
14207 kshitij.so 108
 
14203 kshitij.so 109
        try:
14212 kshitij.so 110
            if data['identifier'] is None or len(data['identifier'].strip())==0:
111
                return {}
112
 
113
            try:
14828 kshitij.so 114
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
14212 kshitij.so 115
                    print "sku id is already updated",data['_id'] 
15913 kshitij.so 116
                    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']}
14212 kshitij.so 117
            except:
118
                pass
119
 
14840 kshitij.so 120
            url = "http://50.116.3.101:8080/mobileapi/dtr-pricing?id=%s"%(data['identifier'])
14212 kshitij.so 121
            lowestPrice = 0.0
122
            instock = 0
123
            req = urllib2.Request(url,headers=headers)
124
            response = urllib2.urlopen(req)
125
            json_input = response.read()
126
            response.close()
127
            priceInfo = json.loads(json_input)
128
            lowestPrice = priceInfo['response']['sellingPrice']
129
            if lowestPrice > 0:
130
                instock = 1
131
            if instock  == 1:
132
                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 133
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestPrice , 'in_stock':instock,'codAvailable':data['codAvailable']}}, multi=True)
14212 kshitij.so 134
            else:
135
                lowestPrice = data['available_price']
136
                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 137
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock,'codAvailable':data['codAvailable']}}, multi=True)
14212 kshitij.so 138
 
15913 kshitij.so 139
            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']}
14834 kshitij.so 140
 
141
        except Exception as e:
142
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
143
            print e
15913 kshitij.so 144
            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']}
14203 kshitij.so 145
 
14207 kshitij.so 146
 
13829 kshitij.so 147
    elif source_id ==3:
148
        try:
13918 kshitij.so 149
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 150
                return {}
13918 kshitij.so 151
 
152
            try:
14828 kshitij.so 153
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
13920 kshitij.so 154
                    print "sku id is already updated",data['_id']
15913 kshitij.so 155
                    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']}
13919 kshitij.so 156
 
157
            except Exception as e:
13920 kshitij.so 158
                print "Exception snapdeal"
13919 kshitij.so 159
                print e
13918 kshitij.so 160
 
15819 kshitij.so 161
            url="http://www.snapdeal.com/acors/json/v2/gvbps?supc=%s&catUrl=&bn=&catId=175&start=0&count=10000"%(data['identifier'])
13829 kshitij.so 162
            req = urllib2.Request(url,headers=headers)
163
            response = urllib2.urlopen(req)
15819 kshitij.so 164
            vendorInfo = json.load(response)
14188 kshitij.so 165
            response.close()
13829 kshitij.so 166
            lowestOfferPrice = 0
167
            inStock = 0
15253 kshitij.so 168
            buyBoxPrice = 0
169
            isBuyBox = 1
15819 kshitij.so 170
            try:
171
                buyBoxStock = vendorInfo['primaryVendor']['buyableInventory']
172
                if buyBoxStock >0:
173
                    buyBoxPrice = vendorInfo['primaryVendor']['sellingPrice']
174
            except:
175
                pass
176
            print buyBoxStock
177
            print buyBoxPrice
178
            sortedVendorsData = sorted(vendorInfo['vendors'], key=itemgetter('sellingPrice'))
15253 kshitij.so 179
            for sortedVendorData in sortedVendorsData:
180
                lowestOfferPrice = float(sortedVendorData['sellingPrice'])
181
                try:
182
                    stock = sortedVendorData['buyableInventory']
183
                except:
184
                    stock = 0
13829 kshitij.so 185
                if stock > 0 and lowestOfferPrice > 0:
186
                    inStock = 1
187
                    break
188
 
189
            print lowestOfferPrice
190
            print inStock
191
            print "*************"
15253 kshitij.so 192
 
193
            if buyBoxPrice != lowestOfferPrice:
194
                isBuyBox = 0
195
 
13829 kshitij.so 196
            if inStock  == 1:
15253 kshitij.so 197
                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 198
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
13829 kshitij.so 199
            else:
13929 kshitij.so 200
                lowestOfferPrice = data['available_price']
15253 kshitij.so 201
                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 202
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
13918 kshitij.so 203
 
15913 kshitij.so 204
            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']}
14834 kshitij.so 205
        except Exception as e:
15266 kshitij.so 206
            print traceback.print_exc()
14834 kshitij.so 207
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
208
            print e
15913 kshitij.so 209
            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']}
13829 kshitij.so 210
 
211
    elif source_id == 2:
212
        try:
13918 kshitij.so 213
            if data['identifier'] is None or len(data['identifier'].strip())==0:
13829 kshitij.so 214
                return {}
13918 kshitij.so 215
 
15609 kshitij.so 216
            if data['_id'] in ignoreItems:
15608 kshitij.so 217
                print "Ignored items returning for %d"%(data['_id'])
15913 kshitij.so 218
                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']}
15608 kshitij.so 219
 
13918 kshitij.so 220
            try:
14828 kshitij.so 221
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
13918 kshitij.so 222
                    print "sku id is already updated",data['_id']
15913 kshitij.so 223
                    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']} 
13918 kshitij.so 224
            except:
225
                pass
226
 
227
            lowestSp = 0
228
            inStock = 0
15253 kshitij.so 229
            buyBoxPrice = 0
230
            isBuyBox = 0
14189 kshitij.so 231
            scraperProductPage = NewFlipkartScraper.FlipkartProductPageScraper()
14121 kshitij.so 232
            try:
233
                if data['marketPlaceUrl']!="" or data['marketPlaceUrl'] !="http://www.flipkart.com/ps/%s"%(data['identifier']):
234
                    result = scraperProductPage.read(data['marketPlaceUrl'])
14124 kshitij.so 235
                    print result
14125 kshitij.so 236
                    if result.get('lowestSp')!=0:
237
                        lowestSp = result.get('lowestSp')
14121 kshitij.so 238
                        inStock = result.get('inStock')
15253 kshitij.so 239
                        buyBoxPrice = result.get('buyBoxPrice')
14121 kshitij.so 240
            except:
241
                print "Unable to scrape product page ",data['identifier']
242
            if lowestSp ==0:
243
                url = "http://www.flipkart.com/ps/%s"%(data['identifier'])
14189 kshitij.so 244
                scraperFk = FlipkartScraper.FlipkartScraper()
15253 kshitij.so 245
                vendorsData, buyBoxInfo = (scraperFk.read(url))
14121 kshitij.so 246
                sortedVendorsData = []
247
                sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
248
                print "data",sortedVendorsData
249
                for vData in sortedVendorsData:
250
                    lowestSp = vData['sellingPrice']
251
                    break
252
                if lowestSp > 0:
253
                    inStock = 1
15975 kshitij.so 254
                try:
255
                    buyBoxPrice = buyBoxInfo[0].get('sellingPrice')
256
                except:
257
                    buyBoxPrice = None
13829 kshitij.so 258
            print lowestSp
259
            print inStock
15253 kshitij.so 260
            if buyBoxPrice is not None and buyBoxPrice == lowestSp:
261
                isBuyBox = 1
13829 kshitij.so 262
            if lowestSp > 0:
15253 kshitij.so 263
                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 264
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp , 'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
13829 kshitij.so 265
            else:
13929 kshitij.so 266
                lowestSp = data['available_price']
15253 kshitij.so 267
                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 268
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock,'codAvailable':data['codAvailable']}}, multi=True)
13918 kshitij.so 269
 
15913 kshitij.so 270
            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']}
14342 kshitij.so 271
 
14834 kshitij.so 272
        except Exception as e:
273
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
274
            print e
15913 kshitij.so 275
            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']}
15902 kshitij.so 276
 
277
    elif source_id == 5:
278
        try:
279
            if data['_id'] in ignoreItems:
280
                print "Ignored items returning for %d"%(data['_id'])
15913 kshitij.so 281
                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']}
15902 kshitij.so 282
 
283
            try:
284
                if ignoreLastUpdated and data['priceUpdatedOn'] > to_java_date(now - timedelta(minutes=5)):
285
                    print "sku id is already updated",data['_id'] 
15913 kshitij.so 286
                    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']}
15902 kshitij.so 287
            except:
288
                pass
289
 
290
 
291
            url = data['marketPlaceUrl']
292
            lowestPrice = 0.0
293
            try:
294
                sc = ShopCluesScraper.ShopCluesScraper()
15951 kshitij.so 295
                url = transformUrl(url, 5)
15902 kshitij.so 296
                productInfo = sc.read(url)
297
            except Exception as e:
15912 kshitij.so 298
                print traceback.print_exc()
16022 kshitij.so 299
                productInfo['price'] = 0.0
300
                productInfo['inStock'] = 0
301
                productInfo['isCod'] = 0
302
 
15902 kshitij.so 303
            print "LowestPrice ",productInfo['price']
304
            if productInfo['price'] > 0 and productInfo['inStock']==1:
305
                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 306
                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 307
            else:
308
                lowestPrice = data['available_price']
309
                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 310
                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 311
 
15912 kshitij.so 312
            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']}
15902 kshitij.so 313
        except Exception as e:
314
            print "Exception for _id %d and source %s"%(data['_id'], source_id)
315
            print e
15913 kshitij.so 316
            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']}
15902 kshitij.so 317
 
13829 kshitij.so 318
    else:
319
        return {}
15902 kshitij.so 320
 
321
 
13918 kshitij.so 322
 
15253 kshitij.so 323
def recomputePoints(item, deal):
324
    try:
325
        nlcPoints = getNlcPoints(item, deal['minNlc'], deal['maxNlc'], deal['available_price'])
326
    except:
327
        print traceback.print_exc()
328
        nlcPoints = deal['nlcPoints']
329
    if item['manualDealThresholdPrice'] >= deal['available_price']:
330
        dealPoints = item['dealPoints']
331
    else:
332
        dealPoints = 0
333
    get_mongo_connection().Catalog.Deals.update({'_id':deal['_id']},{"$set":{'totalPoints':deal['totalPoints'] - deal['nlcPoints'] + nlcPoints - deal['dealPoints'] +dealPoints , 'nlcPoints': nlcPoints, 'dealPoints': dealPoints, 'manualDealThresholdPrice': item['manualDealThresholdPrice']}})
334
 
15266 kshitij.so 335
 
336
def populateNegativeDeals():
337
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
338
    mc.set("negative_deals", negativeDeals, 600)
339
 
340
def recomputeDeal(item):
16017 kshitij.so 341
 
13918 kshitij.so 342
    """Lets recompute deal for this bundle"""
15266 kshitij.so 343
    print "Recomputing for bundleId",item.get('skuBundleId')
344
    skuBundleId = item['skuBundleId']
13829 kshitij.so 345
 
13918 kshitij.so 346
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
347
    bestPrice = float("inf")
348
    bestOne = None
349
    bestSellerPoints = 0
350
    toUpdate = []
16017 kshitij.so 351
    prepaidBestPrice = float("inf")
352
    prepaidBestOne = None
353
    prepaidBestSellerPoints = 0
13918 kshitij.so 354
    for similarItem in similarItems:
15266 kshitij.so 355
        if similarItem['_id'] == item['_id']:
356
            recomputePoints(item, similarItem)
16017 kshitij.so 357
        if similarItem['codAvailable'] ==1:
358
            if mc.get("negative_deals") is None:
359
                populateNegativeDeals()
360
            if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
361
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
362
                continue
363
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
364
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
365
                continue
366
            if similarItem['available_price'] < bestPrice:
367
                bestOne = similarItem
368
                bestPrice = similarItem['available_price']
369
                bestSellerPoints = similarItem['bestSellerPoints']
370
            elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
371
                bestOne = similarItem
372
                bestPrice = similarItem['available_price']
373
                bestSellerPoints = similarItem['bestSellerPoints']
374
            else:
375
                pass
13918 kshitij.so 376
        else:
16017 kshitij.so 377
            if mc.get("negative_deals") is None:
378
                populateNegativeDeals()
379
            if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
380
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
381
                continue
382
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
383
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
384
                continue
385
            if similarItem['available_price'] < prepaidBestPrice:
386
                prepaidBestOne = similarItem
387
                prepaidBestPrice = similarItem['available_price']
388
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
389
            elif similarItem['available_price'] == prepaidBestPrice and prepaidBestSellerPoints < similarItem['bestSellerPoints']:
390
                prepaidBestOne = similarItem
391
                prepaidBestPrice = similarItem['available_price']
392
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
393
            else:
394
                pass
16024 kshitij.so 395
    print "bestOne ", bestOne
396
    print "prepaid best one",  prepaidBestOne
397
    if bestOne is not None or prepaidBestOne is not None:
13918 kshitij.so 398
        for similarItem in similarItems:
399
            toUpdate.append(similarItem['_id'])
16023 kshitij.so 400
        if bestOne is not None:
401
            toUpdate.remove(bestOne['_id'])
402
            get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})
403
        if prepaidBestOne is not None:
404
            toUpdate.remove(prepaidBestOne['_id'])
405
            get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
13918 kshitij.so 406
    if len(toUpdate) > 0:
16017 kshitij.so 407
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)
408
 
14342 kshitij.so 409
    print "Done with recomputing"
13829 kshitij.so 410
 
411
def getLatestPrice(skuBundleId, source_id):
412
    temp = []
413
    itemIds = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId,'source_id' : source_id}))
16026 kshitij.so 414
    item = None
13829 kshitij.so 415
    for item in itemIds:
14309 kshitij.so 416
        item['dealFlag'] = 0
417
        item['dealType'] = 0
15266 kshitij.so 418
        item['dealPoints'] = 0
419
        item['manualDealThresholdPrice'] = None
15912 kshitij.so 420
        if item['source_id'] ==5 and item['rank'] == 0:
421
            continue
15187 kshitij.so 422
        if item['source_id'] ==3:
423
            item['marketPlaceUrl'] = item['marketPlaceUrl']+'?supc='+item.get('identifier')
14309 kshitij.so 424
        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']}))
425
        if len(manualDeals) > 0:
426
            item['dealFlag'] = 1
14760 kshitij.so 427
            item['dealType'] =manualDeals[0]['dealType']
15266 kshitij.so 428
            item['dealPoints'] = manualDeals[0]['dealPoints']
429
            item['manualDealThresholdPrice'] = manualDeals[0]['dealThresholdPrice']
14760 kshitij.so 430
        info = returnLatestPrice(item, source_id)
14794 kshitij.so 431
        print info
14760 kshitij.so 432
        try:
433
            cashBack = getCashBack(item['_id'], item['source_id'], item['category_id'], mc, 'localhost')
14794 kshitij.so 434
            print "CashBack is ",cashBack
14760 kshitij.so 435
            if not cashBack or cashBack.get('cash_back_status')!=1:
14801 kshitij.so 436
                info['cash_back_type'] = 0
437
                info['cash_back'] = 0
14760 kshitij.so 438
            else:
439
                if cashBack['cash_back_type'] in (1,2):
440
                    info['cash_back_type'] = cashBack['cash_back_type']
441
                    info['cash_back'] = float(cashBack['cash_back'])
442
                else:
14801 kshitij.so 443
                    info['cash_back_type'] = 0
444
                    info['cash_back'] = 0
14760 kshitij.so 445
        except Exception as cashBackEx:
14794 kshitij.so 446
            traceback.print_exc()
14760 kshitij.so 447
            print "Error calculating cashback."
448
            info['cash_back_type'] = 0
449
            info['cash_back'] = 0
14794 kshitij.so 450
        print "info is ",info
14760 kshitij.so 451
        temp.append(info)
16026 kshitij.so 452
    if item is not None:
453
        try:
454
            thread = threading.Thread(target=recomputeDeal, args = (item,))
455
            thread.daemon = True
456
            thread.start()    
457
        except:
458
            print traceback.print_exc()
459
            print "Unable to compute deal for ",skuBundleId
13829 kshitij.so 460
    return temp
461
 
13864 kshitij.so 462
def getLatestPriceById(id):
463
    item = list(get_mongo_connection().Catalog.MasterData.find({'_id':id}))
14309 kshitij.so 464
    item[0]['dealFlag'] = 0
465
    item[0]['dealType'] = 0
15266 kshitij.so 466
    item[0]['dealPoints'] = 0
467
    item[0]['manualDealThresholdPrice'] = None
14309 kshitij.so 468
    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']}))
469
    if len(manualDeals) > 0:
470
        item[0]['dealFlag'] = 1
15266 kshitij.so 471
        item[0]['dealType'] =manualDeals[0]['dealType']
472
        item[0]['dealPoints'] = manualDeals[0]['dealPoints']
473
        item[0]['manualDealThresholdPrice'] = manualDeals[0]['dealThresholdPrice']
14367 kshitij.so 474
 
14431 kshitij.so 475
    info = returnLatestPrice(item[0], item[0]['source_id'])
14794 kshitij.so 476
    print info
14367 kshitij.so 477
    try:
14794 kshitij.so 478
        cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'], mc, 'localhost')
479
        print "CashBack is ",cashBack
14760 kshitij.so 480
        if not cashBack or cashBack.get('cash_back_status')!=1:
14801 kshitij.so 481
            info['cash_back_type'] = 0
482
            info['cash_back'] = 0
14760 kshitij.so 483
        else:
484
            if cashBack['cash_back_type'] in (1,2):
485
                info['cash_back_type'] = cashBack['cash_back_type']
486
                info['cash_back'] = float(cashBack['cash_back'])
487
            else:
14801 kshitij.so 488
                info['cash_back_type'] = 0
489
                info['cash_back'] = 0
14760 kshitij.so 490
    except Exception as cashBackEx:
14794 kshitij.so 491
        traceback.print_exc()
14760 kshitij.so 492
        print cashBackEx
493
        print "Error calculating cashback."
494
        info['cash_back_type'] = 0
495
        info['cash_back'] = 0
496
    try:
15273 kshitij.so 497
        thread = threading.Thread(target=recomputeDeal, args = (item[0],))
14367 kshitij.so 498
        thread.daemon = True
499
        thread.start()    
500
    except:
501
        print "Unable to compute deal for ",item[0]['skuBundleId']
14431 kshitij.so 502
    return info
13829 kshitij.so 503
 
14828 kshitij.so 504
def updatePriceForNotificationBundles(skuBundleId):
15266 kshitij.so 505
    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 506
    for item in itemIds:
14833 kshitij.so 507
        print item['_id']
14828 kshitij.so 508
        item['dealFlag'] = 0
509
        item['dealType'] = 0
15266 kshitij.so 510
        item['dealPoints'] = 0
511
        item['manualDealThresholdPrice'] = None
14828 kshitij.so 512
        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']}))
513
        if len(manualDeals) > 0:
514
            item['dealFlag'] = 1
515
            item['dealType'] =manualDeals[0]['dealType']
15266 kshitij.so 516
            item['dealPoints'] = manualDeals[0]['dealPoints']
517
            item['manualDealThresholdPrice'] = manualDeals[0]['dealThresholdPrice']
14828 kshitij.so 518
        info = returnLatestPrice(item, item['source_id'],False)
519
        print info
520
 
13829 kshitij.so 521
def main():
15956 kshitij.so 522
    print datetime.now()
15975 kshitij.so 523
    print "retuned %s"%(str(getLatestPriceById(12391)))
15956 kshitij.so 524
    print datetime.now()
13829 kshitij.so 525
if __name__=='__main__':
13971 kshitij.so 526
    main()
527