Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
13755 kshitij.so 1
import pymongo
2
from elixir import *
3
from shop2020.model.v1.catalog.impl import DataService
4
from shop2020.model.v1.catalog.impl.DataService import Item
5
from shop2020.clients.InventoryClient import InventoryClient
6
from dtr.utils.utils import to_java_date
7
from datetime import datetime, timedelta
8
import time
14258 kshitij.so 9
import optparse
13755 kshitij.so 10
 
14258 kshitij.so 11
parser = optparse.OptionParser()
12
parser.add_option("-h", "--host", dest="hostname",
13
                      default="localhost",
14
                      type="string", help="The HOST where the DB server is running",
15
                      metavar="host")
16
parser.add_option("-m", "--m", dest="mongoHost",
17
                      default="localhost",
18
                      type="string", help="The HOST where the mongo server is running",
19
                      metavar="mongo_host")
13755 kshitij.so 20
 
14258 kshitij.so 21
(options, args) = parser.parse_args()
22
DataService.initialize(db_hostname=options.hostname)
23
 
13755 kshitij.so 24
con = None
25
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4}
26
DISCOUNT_TYPE = {'MRP':1,'DP':2}
27
LATEST_UPDATED_ITEMS = []
28
 
29
now = datetime.now()
30
 
31
class __SkuInfo:
32
 
33
    def __init__(self, _id, skuBundleId, category_id, mrp, available_price, source_id, rank, maxNlc, minNlc, schemeAmount, minDiscount, \
14035 kshitij.so 34
                 maxDiscount, discountType, dp, nlcPoints, bestSellerPoints, totalPoints, status, in_stock, maxprice, brand):
13755 kshitij.so 35
        self._id = _id
36
        self.skuBundleId = skuBundleId
37
        self.category_id = category_id
38
        self.mrp = mrp
39
        self.available_price = available_price
40
        self.source_id = source_id
41
        self.rank = rank
42
        self.maxNlc = maxNlc
43
        self.minNlc = minNlc
44
        self.schemeAmount = schemeAmount
45
        self.minDiscount = minDiscount
46
        self.maxDiscount = maxDiscount
47
        self.discountType = discountType
48
        self.dp = dp
49
        self.nlcPoints = nlcPoints
50
        self.bestSellerPoints = bestSellerPoints
13824 kshitij.so 51
        self.totalPoints = totalPoints
52
        self.status = status
53
        self.in_stock = in_stock
54
        self.maxprice = maxprice
14035 kshitij.so 55
        self.brand = brand
13755 kshitij.so 56
 
57
 
14258 kshitij.so 58
def get_mongo_connection(host=options.mongoHost, port=27017):
13755 kshitij.so 59
    global con
60
    if con is None:
61
        print "Establishing connection %s host and port %d" %(host,port)
62
        try:
63
            con = pymongo.MongoClient(host, port)
64
        except Exception, e:
65
            print e
66
            return None
67
    return con
68
 
69
def populateStuff():
70
    print "Inside populate"
71
    global LATEST_UPDATED_ITEMS
72
    """Fetch latest updated items across portals
73
       and calculate max and min R-Nlc"""
74
    offset= 0
75
    while(True):
76
        print "Fetching records offset %d and limit %d" %(offset,300)
77
        topSkus = list(get_mongo_connection().Catalog.MasterData.find( {"$and":[{'updatedOn': { "$gt": to_java_date(now - timedelta(hours=4))} }, { 'source_id' : { "$in": SOURCE_MAP.values() } }] }).skip(offset).limit(300))
78
        if len((topSkus)) == 0:
79
            break
80
        #topSkus = collection.find( {'_id':664})
81
        for sku in topSkus:
13908 kshitij.so 82
            """Fix this """
83
            #TODO Compute deal flags else where.
13755 kshitij.so 84
            info = __SkuInfo(sku['_id'], sku['skuBundleId'], sku['category_id'], sku['mrp'], sku['available_price'], sku['source_id'], sku['rank'], None, None, 0.0, None, \
14035 kshitij.so 85
                             None, None, None, None, None, None, sku['status'], sku['in_stock'],None,sku['brand'].strip().upper())
13755 kshitij.so 86
            exceptionalNlc = list(get_mongo_connection().Catalog.ExceptionalNlc.find( {"$and" : [ {'sku':info._id}, {'overrideNlc':1} ]} ))
87
            if len(exceptionalNlc) > 0:
88
                """Exceptional nlc found, no need to calculate max and min R-nlc"""
89
                info.maxNlc = exceptionalNlc[0]['maxNlc']
90
                info.minNlc = exceptionalNlc[0]['minNlc']
13824 kshitij.so 91
                info.maxprice = exceptionalNlc[0]['maxNlc']
13755 kshitij.so 92
                LATEST_UPDATED_ITEMS.append(info)
93
                continue
94
 
95
            skuSchemeDetails = list(get_mongo_connection().Catalog.SkuSchemeDetails.find( {'sku':info._id}).sort([('addedOn',pymongo.DESCENDING)]).limit(1))
96
            if len(skuSchemeDetails) > 0:
97
                """Sku scheme details, populate scheme amount (Recently added)"""
13824 kshitij.so 98
 
99
                #TODO Add start date and end date of scehems
100
 
13755 kshitij.so 101
                info.schemeAmount = float(skuSchemeDetails[0]['schemeAmount'])
102
 
103
            skuDealerPrices = list(get_mongo_connection().Catalog.SkuDealerPrices.find( {'sku':info._id} ) )
104
            if len(skuDealerPrices) > 0:
105
                info.dp = skuDealerPrices[0]['dp']
106
            skuDiscount = list(get_mongo_connection().Catalog.SkuDiscountInfo.find( {'sku':info._id} ) )
107
            if len(skuDiscount) > 0:
108
                """Sku rule found, populate max , min Discount and discount type"""
109
                info.maxDiscount = skuDiscount[0]['max_discount']
110
                info.minDiscount = skuDiscount[0]['min_discount']
111
                info.discountType = DISCOUNT_TYPE.get(skuDiscount[0]['discountType'].upper())
112
                LATEST_UPDATED_ITEMS.append(info)
113
                continue
114
 
14035 kshitij.so 115
            categoryDiscount = list(get_mongo_connection().Catalog.CategoryDiscount.find( {"$and" : [{'brand':sku['brand'].strip().upper()}, {'category_id':sku['category_id']} ]} ))
13755 kshitij.so 116
            if len(categoryDiscount) > 0:
117
                info.maxDiscount = categoryDiscount[0]['max_discount']
118
                info.minDiscount = categoryDiscount[0]['min_discount']
119
                info.discountType = DISCOUNT_TYPE.get(categoryDiscount[0]['discountType'].upper())
120
 
121
            LATEST_UPDATED_ITEMS.append(info)
122
        offset = offset + 300
123
    for lol in LATEST_UPDATED_ITEMS:
124
        print lol.__dict__
125
 
126
 
127
def calculateNlc():
128
    global LATEST_UPDATED_ITEMS
129
    populated = 0
130
    while(populated <= len(LATEST_UPDATED_ITEMS)):
131
        inventory_client = InventoryClient().get_client()
132
        for obj in LATEST_UPDATED_ITEMS[populated:300+populated]:
133
            if obj.maxNlc > 0 and obj.minNlc > 0:
134
                continue
135
            saholic_sku = list(get_mongo_connection().Catalog.MasterData.find( {"$and":[{'skuBundleId': obj.skuBundleId}, { 'source_id' : SOURCE_MAP.get('SAHOLIC')}] }))
136
            identifier = None
137
            if len(saholic_sku) > 0:
138
                identifier = saholic_sku[0]['identifier']
139
            if obj.discountType == DISCOUNT_TYPE.get('MRP'):
140
                if obj.mrp == 0:
141
                    """Now mrp is zero, so we have to use saholic MRP"""
142
                    if identifier is not None:
143
                        it = Item.query.filter_by(catalog_item_id=identifier).first()
144
                        obj.mrp = it.mrp
145
                if obj.mrp > 0:
146
                    obj.minNlc = obj.mrp - (obj.mrp * obj.maxDiscount/100) - obj.schemeAmount
13824 kshitij.so 147
                    obj.maxNlc = obj.mrp - (obj.mrp * obj.minDiscount/100) - obj.schemeAmount
13982 kshitij.so 148
                    obj.maxprice = obj.maxNlc  
13755 kshitij.so 149
            elif obj.discountType == DISCOUNT_TYPE.get('DP'):
150
                if obj.dp == 0:
151
                    """Now dp is zero, so we have to use saholic minimum dp for item"""
152
                    if identifier is not None:
153
                        it = Item.query.filter_by(catalog_item_id=identifier).first()
154
                        try:
155
                            vendorPricing = inventory_client.getAllItemPricing(it.id)
156
                            min_dp = min(pricing.dealerPrice for pricing in vendorPricing)
157
                            obj.dp = min_dp 
158
                        except:
159
                            pass
160
                if obj.dp > 0:
161
                    obj.minNlc = obj.dp - (obj.dp * obj.maxDiscount/100) - obj.schemeAmount
13824 kshitij.so 162
                    obj.maxNlc = obj.dp - (obj.dp * obj.minDiscount/100) - obj.schemeAmount
163
                    obj.maxprice = obj.maxNlc   
13755 kshitij.so 164
            else:
165
                """No rule found, use saholic min nlc as max and min R-Nlc"""
166
                if identifier is not None:
167
                    it = Item.query.filter_by(catalog_item_id=identifier).first()
168
                    try:
169
                        vendorPricing = inventory_client.getAllItemPricing(it.id)
170
                        min_nlc = min(pricing.nlc for pricing in vendorPricing)
171
                        obj.maxNlc = min_nlc
13824 kshitij.so 172
                        obj.minNlc = min_nlc
173
                        obj.maxprice = obj.maxNlc   
13755 kshitij.so 174
                    except:
175
                        pass
176
        populated = populated + 300
177
        time.sleep(10) 
178
 
179
def calculateNlcPoints():
180
    global LATEST_UPDATED_ITEMS
181
    for sku in LATEST_UPDATED_ITEMS:
182
        if sku.maxNlc and sku.minNlc:
13824 kshitij.so 183
 
184
            """Create map - TODO"""
185
 
186
            if sku.status == 2:
187
                eolWeight = .60
188
            else:
189
                eolWeight = 1.0
190
            if sku.category_id == 3:
191
                basePointPercentage = 5.0
192
                maxNlcPoints = 200
193
            elif sku.category_id == 5:
194
                basePointPercentage = 8.0
195
                maxNlcPoints = 150
196
            else:
197
                basePointPercentage = 10.0
198
                maxNlcPoints = 150
13755 kshitij.so 199
            discFromMinNlc = (sku.minNlc - sku.available_price)/sku.available_price *100
200
            discFromMaxNlc = (sku.maxNlc - sku.available_price)/sku.available_price *100
201
            if discFromMinNlc > 0:
13824 kshitij.so 202
                nlcPoints = 100/basePointPercentage * discFromMinNlc
13755 kshitij.so 203
            elif discFromMinNlc < 0 and discFromMaxNlc > 0:
204
                nlcPoints = 0
205
            else:
13824 kshitij.so 206
                nlcPoints = 100/basePointPercentage * discFromMinNlc
207
            if (min(nlcPoints,maxNlcPoints)) > 0:
208
                sku.nlcPoints = (min(nlcPoints,maxNlcPoints)) * eolWeight
209
            else:
210
                sku.nlcPoints = (min(nlcPoints,maxNlcPoints))
13755 kshitij.so 211
        else:
212
            sku.nlcPoints = 0
213
 
214
def commitData():
215
    global LATEST_UPDATED_ITEMS
216
    for sku in LATEST_UPDATED_ITEMS:
217
        #get_mongo_connection().Catalog.Deals.update({'_id':sku._id},{'$set' : sku.__dict__},upsert=True,multi=True)
14020 amit.gupta 218
        get_mongo_connection().Catalog.Deals.update({'_id':sku._id},{"$set":sku.__dict__},upsert=True)
13755 kshitij.so 219
 
220
 
221
def addBestSellerPoints():
222
    allItems = list(get_mongo_connection().Catalog.Deals.find({})) 
223
    for sku in allItems:
13824 kshitij.so 224
        bestSellerPoints = list(get_mongo_connection().Catalog.BestSellerPoints.find( {"$and":[{'min_rank': { "$lte": sku['rank'] } }, {'max_rank': { "$gte": sku['rank'] } } , { 'category_id' : sku['category_id'] }, { 'source_id' : sku['source_id'] }] } ))
13755 kshitij.so 225
        if len(bestSellerPoints) > 0:
13824 kshitij.so 226
            print bestSellerPoints[0]['points']
227
            if (bestSellerPoints[0]['points']) > 0:
228
                sku['bestSellerPoints'] = (bestSellerPoints[0]['points']) * bestSellerPoints[0]['weightage']
229
            else:
230
                sku['bestSellerPoints'] = (bestSellerPoints[0]['points'])
13755 kshitij.so 231
        else:
13824 kshitij.so 232
            sku['bestSellerPoints'] = -100
14114 kshitij.so 233
        #sku['totalPoints'] = sku['bestSellerPoints'] + sku['nlcPoints']
234
        get_mongo_connection().Catalog.Deals.update({'_id':sku['_id']},{'$set':{'bestSellerPoints':sku['bestSellerPoints']}},multi=False)
235
 
236
    for sku in allItems:
237
        deal_item = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':sku['skuBundleId']}).sort('bestSellerPoints',pymongo.DESCENDING).limit(1))
14142 kshitij.so 238
        sku['catalogBestSellerPoints'] = deal_item[0]['bestSellerPoints']
14114 kshitij.so 239
        sku['totalPoints'] = sku['catalogBestSellerPoints'] + sku['nlcPoints']
240
        get_mongo_connection().Catalog.Deals.update({'_id':sku['_id']},{'$set':{'catalogBestSellerPoints':sku['catalogBestSellerPoints'],'totalPoints':sku['totalPoints']}},multi=False)
241
 
13755 kshitij.so 242
 
13828 kshitij.so 243
def elimiateSimilarDeals():
13912 kshitij.so 244
    allItems = get_mongo_connection().Catalog.Deals.find().distinct('skuBundleId')
245
    for skuBundleId in allItems:
246
        print skuBundleId
247
        similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
13828 kshitij.so 248
        bestPrice = float("inf")
249
        bestOne = None
250
        bestSellerPoints = 0
251
        toUpdate = []
252
        for similarItem in similarItems:
13973 kshitij.so 253
            if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price']:
13828 kshitij.so 254
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
255
                continue
256
            if similarItem['available_price'] < bestPrice:
257
                bestOne = similarItem
258
                bestPrice = similarItem['available_price']
259
                bestSellerPoints = similarItem['bestSellerPoints']
260
            elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
261
                bestOne = similarItem
262
                bestPrice = similarItem['available_price']
263
                bestSellerPoints = similarItem['bestSellerPoints']
264
            else:
265
                pass
266
        if bestOne is not None:
267
            for similarItem in similarItems:
268
                toUpdate.append(similarItem['_id'])
269
            toUpdate.remove(bestOne['_id'])
270
            get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
271
        if len(toUpdate) > 0:
13908 kshitij.so 272
            get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
13755 kshitij.so 273
 
274
def main():
275
    populateStuff()
276
    calculateNlc()
277
    calculateNlcPoints()
278
    commitData()
279
    addBestSellerPoints()
13828 kshitij.so 280
    elimiateSimilarDeals()
13755 kshitij.so 281
 
13828 kshitij.so 282
 
13755 kshitij.so 283
if __name__=='__main__':
284
    main()