Subversion Repositories SmartDukaan

Rev

Rev 19190 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
16407 kshitij.so 1
import pymongo
2
from dtr.utils.utils import to_java_date, getNlcPoints
3
from datetime import datetime, timedelta
4
from operator import itemgetter
5
from dtr.utils import PaytmOfferScraper, PaytmScraper
6
from multiprocessing import Pool as ThreadPool
7
from multiprocessing import cpu_count
8
import optparse
9
from dtr.storage.MemCache import MemCache
20347 kshitij.so 10
from dtr.utils.utils import getCashBack, DEAL_PRIORITY
16407 kshitij.so 11
import traceback
16414 kshitij.so 12
from dtr.CouponMaster import addToPaytmMaster
16417 kshitij.so 13
from dtr.storage import DataService
16407 kshitij.so 14
 
15
con = None
16
 
17
parser = optparse.OptionParser()
18
parser.add_option("-m", "--m", dest="mongoHost",
19
                      default="localhost",
20
                      type="string", help="The HOST where the mongo server is running",
21
                      metavar="mongo_host")
22
 
23
(options, args) = parser.parse_args()
24
 
25
mc = MemCache(options.mongoHost)
26
 
16417 kshitij.so 27
DataService.initialize(db_hostname=options.mongoHost)
28
 
16407 kshitij.so 29
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4, 'SHOPCLUES.COM':5,'PAYTM.COM':6}
30
 
19190 kshitij.so 31
def getNetPriceForItem(itemId, source_id, category_id ,price):
32
    cash_back_type = 0
33
    cash_back = 0
34
    try:
35
        cashBack = getCashBack(itemId, source_id, category_id, mc, options.mongoHost)
36
        if not cashBack or cashBack.get('cash_back_status')!=1:
37
            cash_back_type = 0
38
            cash_back = 0 
39
 
40
        else:
41
            if cashBack['cash_back_type'] in (1,2):
42
 
43
                if cashBack.get('maxCashBack') is not None:
44
 
45
                    if cashBack.get('cash_back_type') ==1 and (float(cashBack.get('cash_back'))*price)/100 > cashBack.get('maxCashBack'):
46
                        cashBack['cash_back_type'] = 2
47
                        cashBack['cash_back'] = cashBack['maxCashBack']
48
                    elif cashBack.get('cash_back_type') ==2 and cashBack.get('cash_back') > cashBack.get('maxCashBack'):
49
                        cashBack['cash_back'] = cashBack['maxCashBack']
50
                    else:
51
                        pass
52
 
53
 
54
 
55
                cash_back_type = cashBack['cash_back_type']
56
                cash_back = float(cashBack['cash_back'])
57
    except Exception as cashBackEx:
58
        pass
59
 
60
    if cash_back_type ==1:
61
        return (price - float(cash_back)*price/100)
62
    elif cash_back_type ==2:
63
        return (price - cash_back)
64
    else:
65
        return price
66
 
67
 
16407 kshitij.so 68
def get_mongo_connection(host=options.mongoHost, port=27017):
69
    global con
70
    if con is None:
71
        print "Establishing connection %s host and port %d" %(host,port)
72
        try:
73
            con = pymongo.MongoClient(host, port)
74
        except Exception, e:
75
            print e
76
            return None
77
    return con
78
 
79
def populate():
80
    toScrapMap = {}
81
    bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0}}))
82
    for bestSeller in bestSellers: 
83
        paytmBestSellers = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':6}))
84
        for data in paytmBestSellers:
85
            if not toScrapMap.has_key(data['_id']):
86
                data['dealFlag'] = 0
87
                data['dealType'] = 0
88
                toScrapMap[data['_id']] = data
89
    dealFlagged = list(get_mongo_connection().Catalog.Deals.find({'source_id':6,'showDeal':1,'totalPoints':{'$gt':-100}}))
90
    for deal in dealFlagged:
91
        if not toScrapMap.has_key(deal['_id']):
92
            data = list(get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']}))
93
            data[0]['dealFlag'] = 0
94
            data[0]['dealType'] = 0
95
            toScrapMap[deal['_id']] = data[0]
96
    manualDeals = list(get_mongo_connection().Catalog.ManualDeals.find({'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())},'source_id':6}))
97
    for manualDeal in manualDeals:
98
        if not toScrapMap.has_key(manualDeal['sku']):
99
            data = list(get_mongo_connection().Catalog.MasterData.find({'_id':manualDeal['sku']}))
100
            if len(data) > 0:
101
                data[0]['dealFlag'] = 1
102
                data[0]['dealType'] = manualDeal['dealType']
103
                toScrapMap[manualDeal['sku']] = data[0]
104
        else:
105
            data = toScrapMap.get(manualDeal['sku'])
106
            data['dealFlag'] = 1
107
            data['dealType'] = manualDeal['dealType']
16414 kshitij.so 108
    for val in toScrapMap.values():
109
        scrapePaytm(val)
16407 kshitij.so 110
    print "joining threads at %s"%(str(datetime.now()))
111
 
112
def scrapePaytm(data):
113
    if data['source_id']!=6:
114
        return
115
    if data['identifier'] is None or len(data['identifier'].strip())==0:
116
        print "returning in valid identifier"
117
        return
118
 
16506 kshitij.so 119
    if data.get('ignorePricing') ==1:
16407 kshitij.so 120
        print "Ignored items returning for %d"%(data['_id'])
16506 kshitij.so 121
        return
122
 
16407 kshitij.so 123
 
124
    try:
125
        if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):
126
            print "sku id is already updated %d" %(data['_id']) 
127
            return
128
    except:
129
        pass
130
 
131
    paytmScraper = PaytmScraper.PaytmScraper()
132
    url = "https://catalog.paytm.com/v1/mobile/product/%s"%(data['identifier'].strip())
133
    try:
134
        result = paytmScraper.read(url)
16414 kshitij.so 135
        print result
16407 kshitij.so 136
        effective_price = result.get('offerPrice')
16463 kshitij.so 137
        gross_price = effective_price
16407 kshitij.so 138
        coupon = ""
18283 kshitij.so 139
        shareUrl = result.get('shareUrl')
140
        if shareUrl is None:
141
            shareUrl = data['marketPlaceUrl']
16414 kshitij.so 142
        print result['offerUrl']
16407 kshitij.so 143
        try:
144
            offers = PaytmOfferScraper.fetchOffers(result['offerUrl'])
16414 kshitij.so 145
            try:
146
                addToPaytmMaster(offers.get('codes'))
147
            except:
148
                print "Error in adding coupon"
149
                traceback.print_exc()
16407 kshitij.so 150
            bestOffer = {}
151
            for offer_data in offers.get('codes'):
16414 kshitij.so 152
                if effective_price > offer_data.get('effective_price'):
16407 kshitij.so 153
                    effective_price = offer_data.get('effective_price')
154
                    bestOffer = offer_data
155
                    coupon = bestOffer.get('code')
156
        except:
16414 kshitij.so 157
            traceback.print_exc()
158
        print "coupon code",coupon
16470 kshitij.so 159
        if len(coupon) > 0:
160
            result['codAvailable'] = 0
16407 kshitij.so 161
        available_price = effective_price 
162
        if result['inStock']:
19190 kshitij.so 163
            if result['codAvailable'] ==0:
164
                netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('PAYTM.COM'), data['category_id'], gross_price)
165
            else:
166
                netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('PAYTM.COM'), data['category_id'], available_price)
167
 
18283 kshitij.so 168
            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}})
19190 kshitij.so 169
            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,'netPriceAfterCashBack':netPriceAfterCashBack}})
16407 kshitij.so 170
        else:
19190 kshitij.so 171
            if data['codAvailable'] ==0:
172
                netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('PAYTM.COM'), data['category_id'], data['gross_price'])
173
            else:
174
                netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('PAYTM.COM'), data['category_id'], data['available_price'])
175
 
18283 kshitij.so 176
            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}})
19190 kshitij.so 177
            get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0,'codAvailable':result.get('codAvailable'),'netPriceAfterCashBack':netPriceAfterCashBack}})
16407 kshitij.so 178
 
179
    except:
19190 kshitij.so 180
        if data['codAvailable'] ==0:
181
            netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('PAYTM.COM'), data['category_id'], data['gross_price'])
182
        else:
183
            netPriceAfterCashBack = getNetPriceForItem(data['_id'], SOURCE_MAP.get('PAYTM.COM'), data['category_id'], data['available_price'])
184
 
185
 
16407 kshitij.so 186
        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}})
19190 kshitij.so 187
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0,'netPriceAfterCashBack':netPriceAfterCashBack}})
16407 kshitij.so 188
 
189
 
190
    try:
191
        recomputeDeal(data)
192
    except:
193
        print "Unable to compute deal for %s"%(data['skuBundleId'])
194
 
16506 kshitij.so 195
#def recomputePoints(item, deal):
196
#    try:
197
#        if item.get('available_price') == deal['available_price']:
198
#            print "No need to compute points for %d , as price is still same" %(item['_id'])
199
#            return
200
#        nlcPoints = getNlcPoints(item, deal['minNlc'], deal['maxNlc'], deal['available_price'])
201
#    except:
202
#        print traceback.print_exc()
203
#        nlcPoints = deal['nlcPoints']
204
#    
205
#    bundleDealPoints = list(get_mongo_connection().Catalog.DealPoints.find({'skuBundleId':item['skuBundleId'],'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())}}))
206
#    if len(bundleDealPoints) > 0:
207
#        item['manualDealThresholdPrice'] = bundleDealPoints[0]['dealThresholdPrice']
208
#        dealPoints = bundleDealPoints[0]['dealPoints']
209
#    else:
210
#        dealPoints = 0
211
#        item['manualDealThresholdPrice'] = None
212
#    
213
#    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']}})
16407 kshitij.so 214
 
215
def populateNegativeDeals():
216
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
217
    mc.set("negative_deals", negativeDeals, 600)  
218
 
219
def recomputeDeal(item):
220
    """Lets recompute deal for this bundle"""
221
    print "Recomputing for bundleId %d" %(item.get('skuBundleId'))
222
    skuBundleId = item['skuBundleId']
223
 
19190 kshitij.so 224
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('netPriceAfterCashBack',pymongo.ASCENDING)]))
16407 kshitij.so 225
    bestPrice = float("inf")
226
    bestOne = None
227
    bestSellerPoints = 0
228
    toUpdate = []
229
    prepaidBestPrice = float("inf")
230
    prepaidBestOne = None
231
    prepaidBestSellerPoints = 0
232
    for similarItem in similarItems:
233
        if similarItem['codAvailable'] ==1:
234
            if mc.get("negative_deals") is None:
235
                populateNegativeDeals()
236
            if similarItem['in_stock'] == 0  or similarItem['_id'] in mc.get("negative_deals"):
237
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
238
                continue
239
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
240
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
241
                continue
19190 kshitij.so 242
            if similarItem.get('netPriceAfterCashBack') < bestPrice:
16407 kshitij.so 243
                bestOne = similarItem
19190 kshitij.so 244
                bestPrice = similarItem.get('netPriceAfterCashBack')
16407 kshitij.so 245
                bestSellerPoints = similarItem['bestSellerPoints']
20347 kshitij.so 246
            elif similarItem.get('netPriceAfterCashBack') == bestPrice:
247
 
248
                try:
249
                    if (DEAL_PRIORITY.index(int(similarItem['source_id'])) > DEAL_PRIORITY.index(int(bestOne['source_id']))):
250
                        continue
251
                except:
252
                    traceback.print_exc()
253
 
16407 kshitij.so 254
                bestOne = similarItem
19190 kshitij.so 255
                bestPrice = similarItem.get('netPriceAfterCashBack')
16407 kshitij.so 256
                bestSellerPoints = similarItem['bestSellerPoints']
257
            else:
258
                pass
259
        else:
260
            if mc.get("negative_deals") is None:
261
                populateNegativeDeals()
262
            if similarItem['in_stock'] == 0  or similarItem['_id'] in mc.get("negative_deals"):
263
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
264
                continue
265
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
266
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
267
                continue
19190 kshitij.so 268
            if similarItem.get('netPriceAfterCashBack') < prepaidBestPrice:
16407 kshitij.so 269
                prepaidBestOne = similarItem
19190 kshitij.so 270
                prepaidBestPrice = similarItem.get('netPriceAfterCashBack')
16407 kshitij.so 271
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
20347 kshitij.so 272
            elif similarItem.get('netPriceAfterCashBack') == prepaidBestPrice:
273
 
274
                try:
275
                    if (DEAL_PRIORITY.index(int(similarItem['source_id'])) > DEAL_PRIORITY.index(int(bestOne['source_id']))):
276
                        continue
277
                except:
278
                    traceback.print_exc()
279
 
16407 kshitij.so 280
                prepaidBestOne = similarItem
19190 kshitij.so 281
                prepaidBestPrice = similarItem.get('netPriceAfterCashBack')
16407 kshitij.so 282
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
283
            else:
284
                pass
285
    if bestOne is not None or prepaidBestOne is not None:
286
        for similarItem in similarItems:
287
            toUpdate.append(similarItem['_id'])
288
        if bestOne is not None:
289
            toUpdate.remove(bestOne['_id'])
290
            get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})
291
        if prepaidBestOne is not None:
292
            if bestOne is not None:
19190 kshitij.so 293
                if prepaidBestOne.get('netPriceAfterCashBack') < bestOne.get('netPriceAfterCashBack'): 
16407 kshitij.so 294
                    toUpdate.remove(prepaidBestOne['_id'])
295
                    get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
296
            else:
297
                toUpdate.remove(prepaidBestOne['_id'])
298
                get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
299
    if len(toUpdate) > 0:
300
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)
301
 
19190 kshitij.so 302
 
16407 kshitij.so 303
def main():
304
    populate()
305
 
306
if __name__=='__main__':
307
    main()