Subversion Repositories SmartDukaan

Rev

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