Subversion Repositories SmartDukaan

Rev

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