Subversion Repositories SmartDukaan

Rev

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