Subversion Repositories SmartDukaan

Rev

Rev 16463 | Rev 16506 | 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
10
from dtr.utils.utils import getCashBack
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
ignoreItems = []
30
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4, 'SHOPCLUES.COM':5,'PAYTM.COM':6}
31
 
32
def get_mongo_connection(host=options.mongoHost, port=27017):
33
    global con
34
    if con is None:
35
        print "Establishing connection %s host and port %d" %(host,port)
36
        try:
37
            con = pymongo.MongoClient(host, port)
38
        except Exception, e:
39
            print e
40
            return None
41
    return con
42
 
43
def populate():
44
    toScrapMap = {}
45
    bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0}}))
46
    for bestSeller in bestSellers: 
47
        paytmBestSellers = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':6}))
48
        for data in paytmBestSellers:
49
            if not toScrapMap.has_key(data['_id']):
50
                data['dealFlag'] = 0
51
                data['dealType'] = 0
52
                data['dealPoints'] = 0
53
                data['manualDealThresholdPrice'] = None
54
                toScrapMap[data['_id']] = data
55
    dealFlagged = list(get_mongo_connection().Catalog.Deals.find({'source_id':6,'showDeal':1,'totalPoints':{'$gt':-100}}))
56
    for deal in dealFlagged:
57
        if not toScrapMap.has_key(deal['_id']):
58
            data = list(get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']}))
59
            data[0]['dealFlag'] = 0
60
            data[0]['dealType'] = 0
61
            data[0]['dealPoints'] = 0
62
            data[0]['manualDealThresholdPrice'] = None
63
            toScrapMap[deal['_id']] = data[0]
64
    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}))
65
    for manualDeal in manualDeals:
66
        if not toScrapMap.has_key(manualDeal['sku']):
67
            data = list(get_mongo_connection().Catalog.MasterData.find({'_id':manualDeal['sku']}))
68
            if len(data) > 0:
69
                data[0]['dealFlag'] = 1
70
                data[0]['dealType'] = manualDeal['dealType']
71
                data[0]['dealPoints'] = manualDeal['dealPoints']
72
                data[0]['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
73
                toScrapMap[manualDeal['sku']] = data[0]
74
        else:
75
            data = toScrapMap.get(manualDeal['sku'])
76
            data['dealFlag'] = 1
77
            data['dealType'] = manualDeal['dealType']
78
            data['dealPoints'] = manualDeal['dealPoints']
79
            data['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
16414 kshitij.so 80
    for val in toScrapMap.values():
81
        scrapePaytm(val)
16407 kshitij.so 82
    print "joining threads at %s"%(str(datetime.now()))
83
 
84
def scrapePaytm(data):
85
    if data['source_id']!=6:
86
        return
87
    if data['identifier'] is None or len(data['identifier'].strip())==0:
88
        print "returning in valid identifier"
89
        return
90
 
91
    if data['_id'] in ignoreItems:
92
        print "Ignored items returning for %d"%(data['_id'])
93
        return 
94
 
95
    try:
96
        if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):
97
            print "sku id is already updated %d" %(data['_id']) 
98
            return
99
    except:
100
        pass
101
 
102
    paytmScraper = PaytmScraper.PaytmScraper()
103
    url = "https://catalog.paytm.com/v1/mobile/product/%s"%(data['identifier'].strip())
104
    try:
105
        result = paytmScraper.read(url)
16414 kshitij.so 106
        print result
16407 kshitij.so 107
        effective_price = result.get('offerPrice')
16463 kshitij.so 108
        gross_price = effective_price
16407 kshitij.so 109
        coupon = ""
16414 kshitij.so 110
        print result['offerUrl']
16407 kshitij.so 111
        try:
112
            offers = PaytmOfferScraper.fetchOffers(result['offerUrl'])
16414 kshitij.so 113
            try:
114
                addToPaytmMaster(offers.get('codes'))
115
            except:
116
                print "Error in adding coupon"
117
                traceback.print_exc()
16407 kshitij.so 118
            bestOffer = {}
119
            for offer_data in offers.get('codes'):
16414 kshitij.so 120
                if effective_price > offer_data.get('effective_price'):
16407 kshitij.so 121
                    effective_price = offer_data.get('effective_price')
122
                    bestOffer = offer_data
123
                    coupon = bestOffer.get('code')
124
        except:
16414 kshitij.so 125
            traceback.print_exc()
126
        print "coupon code",coupon
16470 kshitij.so 127
        if len(coupon) > 0:
128
            result['codAvailable'] = 0
16407 kshitij.so 129
        available_price = effective_price 
130
        if result['inStock']:
16463 kshitij.so 131
            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}})
132
            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}})
16407 kshitij.so 133
        else:
16414 kshitij.so 134
            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}})
135
            get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0,'codAvailable':result.get('codAvailable')}})
16407 kshitij.so 136
 
137
    except:
138
        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}})
139
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':0}})
140
 
141
 
142
 
143
    try:
144
        recomputeDeal(data)
145
    except:
146
        print "Unable to compute deal for %s"%(data['skuBundleId'])
147
 
148
def recomputePoints(item, deal):
149
    try:
150
        if item.get('available_price') == deal['available_price']:
151
            print "No need to compute points for %d , as price is still same" %(item['_id'])
16418 kshitij.so 152
            return
16407 kshitij.so 153
        nlcPoints = getNlcPoints(item, deal['minNlc'], deal['maxNlc'], deal['available_price'])
154
    except:
155
        print traceback.print_exc()
156
        nlcPoints = deal['nlcPoints']
157
    if item['manualDealThresholdPrice'] >= deal['available_price']:
158
        dealPoints = item['dealPoints']
159
    else:
160
        dealPoints = 0
161
    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']}})
162
 
163
def populateNegativeDeals():
164
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
165
    mc.set("negative_deals", negativeDeals, 600)  
166
 
167
def recomputeDeal(item):
168
    """Lets recompute deal for this bundle"""
169
    print "Recomputing for bundleId %d" %(item.get('skuBundleId'))
170
    skuBundleId = item['skuBundleId']
171
 
172
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
173
    bestPrice = float("inf")
174
    bestOne = None
175
    bestSellerPoints = 0
176
    toUpdate = []
177
    prepaidBestPrice = float("inf")
178
    prepaidBestOne = None
179
    prepaidBestSellerPoints = 0
180
    for similarItem in similarItems:
181
        if similarItem['_id'] == item['_id']:
182
            try:
183
                recomputePoints(item, similarItem)
184
            except:
185
                traceback.print_exc()
186
        if similarItem['codAvailable'] ==1:
187
            if mc.get("negative_deals") is None:
188
                populateNegativeDeals()
189
            if similarItem['in_stock'] == 0  or similarItem['_id'] in mc.get("negative_deals"):
190
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
191
                continue
192
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
193
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
194
                continue
195
            if similarItem['available_price'] < bestPrice:
196
                bestOne = similarItem
197
                bestPrice = similarItem['available_price']
198
                bestSellerPoints = similarItem['bestSellerPoints']
199
            elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
200
                bestOne = similarItem
201
                bestPrice = similarItem['available_price']
202
                bestSellerPoints = similarItem['bestSellerPoints']
203
            else:
204
                pass
205
        else:
206
            if mc.get("negative_deals") is None:
207
                populateNegativeDeals()
208
            if similarItem['in_stock'] == 0  or similarItem['_id'] in mc.get("negative_deals"):
209
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
210
                continue
211
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
212
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
213
                continue
214
            if similarItem['available_price'] < prepaidBestPrice:
215
                prepaidBestOne = similarItem
216
                prepaidBestPrice = similarItem['available_price']
217
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
218
            elif similarItem['available_price'] == prepaidBestPrice and prepaidBestSellerPoints < similarItem['bestSellerPoints']:
219
                prepaidBestOne = similarItem
220
                prepaidBestPrice = similarItem['available_price']
221
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
222
            else:
223
                pass
224
    if bestOne is not None or prepaidBestOne is not None:
225
        for similarItem in similarItems:
226
            toUpdate.append(similarItem['_id'])
227
        if bestOne is not None:
228
            toUpdate.remove(bestOne['_id'])
229
            get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})
230
        if prepaidBestOne is not None:
231
            if bestOne is not None:
232
                if prepaidBestOne['available_price'] < bestOne['available_price']: 
233
                    toUpdate.remove(prepaidBestOne['_id'])
234
                    get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
235
            else:
236
                toUpdate.remove(prepaidBestOne['_id'])
237
                get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
238
    if len(toUpdate) > 0:
239
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)
240
 
241
def main():
242
    populate()
243
 
244
if __name__=='__main__':
245
    main()