Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
14305 amit.gupta 1
from bson.objectid import ObjectId
2
from datetime import datetime, timedelta
3
from dtr.config import PythonPropertyReader
13927 amit.gupta 4
from dtr.main import Store
14531 kshitij.so 5
from dtr.dao import FeaturedDeals
14037 kshitij.so 6
from dtr.storage import DataService
7
from dtr.storage.DataService import price_preferences, brand_preferences, \
15074 kshitij.so 8
    user_actions, Brands
14037 kshitij.so 9
from dtr.storage.MemCache import MemCache
14305 amit.gupta 10
from dtr.utils.utils import to_java_date
11
from elixir import *
12
from operator import itemgetter
13
import pymongo
14322 kshitij.so 14
import re
14791 kshitij.so 15
import traceback
13572 kshitij.so 16
 
17
con = None
18
 
14037 kshitij.so 19
DataService.initialize(db_hostname="localhost")
20
mc = MemCache("127.0.0.1")
21
 
14482 kshitij.so 22
SOURCE_MAP = {1:'AMAZON',2:'FLIPKART',3:'SNAPDEAL',4:'SAHOLIC'}
23
 
13572 kshitij.so 24
def get_mongo_connection(host='localhost', port=27017):
25
    global con
26
    if con is None:
27
        print "Establishing connection %s host and port %d" %(host,port)
28
        try:
29
            con = pymongo.MongoClient(host, port)
30
        except Exception, e:
31
            print e
32
            return None
33
    return con
34
 
13907 kshitij.so 35
def populateCashBack():
13921 kshitij.so 36
    print "Populating cashback"
37
    cashBackMap = {}
38
    itemCashBackMap = {}
13907 kshitij.so 39
    cashBack = list(get_mongo_connection().Catalog.CategoryCashBack.find())
40
    for row in cashBack:
13970 kshitij.so 41
        temp_map = {}
42
        temp_list = []
13907 kshitij.so 43
        if cashBackMap.has_key(row['source_id']):
44
            arr = cashBackMap.get(row['source_id'])
45
            for val in arr:
46
                temp_list.append(val)
47
            temp_map[row['category_id']] = row
48
            temp_list.append(temp_map)
49
            cashBackMap[row['source_id']] = temp_list 
50
        else:
51
            temp_map[row['category_id']] = row
52
            temp_list.append(temp_map)
53
            cashBackMap[row['source_id']] = temp_list
13921 kshitij.so 54
    itemCashBack = list(get_mongo_connection().Catalog.ItemCashBack.find())
55
    for row in itemCashBack:
56
        if not itemCashBackMap.has_key(row['skuId']):
57
            itemCashBackMap[row['skuId']] = row
14761 kshitij.so 58
    mc.set("item_cash_back", itemCashBackMap, 24 * 60 * 60)
59
    mc.set("category_cash_back", cashBackMap, 24 * 60 * 60)
13907 kshitij.so 60
 
13572 kshitij.so 61
def addCategoryDiscount(data):
13970 kshitij.so 62
    collection = get_mongo_connection().Catalog.CategoryDiscount
13572 kshitij.so 63
    query = []
64
    data['brand'] = data['brand'].strip().upper()
13970 kshitij.so 65
    data['discountType'] = data['discountType'].upper().strip()
13572 kshitij.so 66
    query.append({"brand":data['brand']})
67
    query.append({"category_id":data['category_id']})
68
    r = collection.find({"$and":query})
69
    if r.count() > 0:
13639 kshitij.so 70
        return {0:"Brand & Category info already present."}
13572 kshitij.so 71
    else:
72
        collection.insert(data)
13970 kshitij.so 73
        get_mongo_connection().Catalog.MasterData.update({'brand':data['brand'],'category_id':data['category_id']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13639 kshitij.so 74
        return {1:"Data added successfully"}
13572 kshitij.so 75
 
13970 kshitij.so 76
def updateCategoryDiscount(data,_id):
77
    try:
78
        collection = get_mongo_connection().Catalog.CategoryDiscount
79
        collection.update({'_id':ObjectId(_id)},{"$set":{'min_discount':data['min_discount'],'max_discount':data['max_discount'],'discountType':data['discountType'].upper().strip()}},upsert=False, multi = False)
80
        get_mongo_connection().Catalog.MasterData.update({'brand':data['brand'],'category_id':data['category_id']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
81
        return {1:"Data updated successfully"}
82
    except:
83
        return {0:"Data not updated."}
84
 
85
 
13572 kshitij.so 86
def getAllCategoryDiscount():
87
    data = []
13970 kshitij.so 88
    collection = get_mongo_connection().Catalog.CategoryDiscount
13572 kshitij.so 89
    cursor = collection.find()
90
    for val in cursor:
91
        data.append(val)
92
    return data
93
 
14553 kshitij.so 94
def __getBundledSkusfromSku(sku):
95
    masterData =  get_mongo_connection().Catalog.MasterData.find_one({"_id":sku},{"skuBundleId":1})
96
    if masterData is not None:
97
        return list(get_mongo_connection().Catalog.MasterData.find({"skuBundleId":masterData.get('skuBundleId')},{'_id':1,'skuBundleId':1}))
98
    else:
99
        return []
13572 kshitij.so 100
 
14553 kshitij.so 101
def addSchemeDetailsForSku(data, multi):
102
    if multi ==1:
103
        skuIds = __getBundledSkusfromSku(data['sku'])
104
        for sku in skuIds:
105
            collection = get_mongo_connection().Catalog.SkuSchemeDetails
106
            data['sku'] = sku.get('_id')
107
            data['addedOn'] = to_java_date(datetime.now())
14558 kshitij.so 108
            data.pop('_id',None)
14553 kshitij.so 109
            collection.insert(data)
110
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14559 kshitij.so 111
        return {1:"Data added successfully"}
14553 kshitij.so 112
    else:
113
        collection = get_mongo_connection().Catalog.SkuSchemeDetails
114
        data['addedOn'] = to_java_date(datetime.now())
115
        collection.insert(data)
116
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
117
        return {1:"Data added successfully"}
118
 
14069 kshitij.so 119
def getAllSkuWiseSchemeDetails(offset, limit):
13572 kshitij.so 120
    data = []
13970 kshitij.so 121
    collection = get_mongo_connection().Catalog.SkuSchemeDetails
14071 kshitij.so 122
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 123
    for val in cursor:
14069 kshitij.so 124
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
125
        if len(master) > 0:
126
            val['brand'] = master[0]['brand']
127
            val['source_product_name'] = master[0]['source_product_name']
128
            val['skuBundleId'] = master[0]['skuBundleId']
129
        else:
130
            val['brand'] = ""
131
            val['source_product_name'] = ""
132
            val['skuBundleId'] = ""
13572 kshitij.so 133
        data.append(val)
134
    return data
135
 
14553 kshitij.so 136
def addSkuDiscountInfo(data, multi):
137
    if multi != 1:
138
        collection = get_mongo_connection().Catalog.SkuDiscountInfo
139
        cursor = collection.find({"sku":data['sku']})
140
        if cursor.count() > 0:
141
            return {0:"Sku information already present."}
142
        else:
143
            collection.insert(data)
144
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
145
            return {1:"Data added successfully"}
13572 kshitij.so 146
    else:
14553 kshitij.so 147
        skuIds = __getBundledSkusfromSku(data['sku'])
148
        for sku in skuIds:
149
            data['sku'] = sku.get('_id')
150
            collection = get_mongo_connection().Catalog.SkuDiscountInfo
151
            cursor = collection.find({"sku":data['sku']})
152
            if cursor.count() > 0:
153
                continue
154
            else:
14558 kshitij.so 155
                data.pop('_id',None)
14553 kshitij.so 156
                collection.insert(data)
157
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13639 kshitij.so 158
        return {1:"Data added successfully"}
13572 kshitij.so 159
 
13970 kshitij.so 160
def getallSkuDiscountInfo(offset, limit):
13572 kshitij.so 161
    data = []
13970 kshitij.so 162
    collection = get_mongo_connection().Catalog.SkuDiscountInfo
163
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 164
    for val in cursor:
13970 kshitij.so 165
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
166
        if len(master) > 0:
14069 kshitij.so 167
            val['brand'] = master[0]['brand']
168
            val['source_product_name'] = master[0]['source_product_name']
169
            val['skuBundleId'] = master[0]['skuBundleId']
13970 kshitij.so 170
        else:
171
            val['brand'] = ""
172
            val['source_product_name'] = ""
173
            val['skuBundleId'] = ""
13572 kshitij.so 174
        data.append(val)
175
    return data
176
 
13970 kshitij.so 177
def updateSkuDiscount(data,_id):
178
    try:
179
        collection = get_mongo_connection().Catalog.SkuDiscountInfo
180
        collection.update({'_id':ObjectId(_id)},{"$set":{'min_discount':data['min_discount'],'max_discount':data['max_discount'],'discountType':data['discountType'].upper().strip()}},upsert=False, multi = False)
181
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
182
        return {1:"Data updated successfully"}
183
    except:
184
        return {0:"Data not updated."}
185
 
186
 
14553 kshitij.so 187
def addExceptionalNlc(data, multi):
188
    if multi!=1:
189
        collection = get_mongo_connection().Catalog.ExceptionalNlc
190
        cursor = collection.find({"sku":data['sku']})
191
        if cursor.count() > 0:
192
            return {0:"Sku information already present."}
193
        else:
194
            collection.insert(data)
195
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
196
            return {1:"Data added successfully"}
13572 kshitij.so 197
    else:
14553 kshitij.so 198
        skuIds = __getBundledSkusfromSku(data['sku'])
199
        for sku in skuIds:
200
            data['sku'] = sku.get('_id')
201
            collection = get_mongo_connection().Catalog.ExceptionalNlc
202
            cursor = collection.find({"sku":data['sku']})
203
            if cursor.count() > 0:
204
                continue
205
            else:
14558 kshitij.so 206
                data.pop('_id',None)
14553 kshitij.so 207
                collection.insert(data)
208
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13639 kshitij.so 209
        return {1:"Data added successfully"}
13572 kshitij.so 210
 
13970 kshitij.so 211
def getAllExceptionlNlcItems(offset, limit):
13572 kshitij.so 212
    data = []
13970 kshitij.so 213
    collection = get_mongo_connection().Catalog.ExceptionalNlc
14071 kshitij.so 214
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 215
    for val in cursor:
13970 kshitij.so 216
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
217
        if len(master) > 0:
14069 kshitij.so 218
            val['brand'] = master[0]['brand']
219
            val['source_product_name'] = master[0]['source_product_name']
220
            val['skuBundleId'] = master[0]['skuBundleId']
13970 kshitij.so 221
        else:
222
            val['brand'] = ""
223
            val['source_product_name'] = ""
224
            val['skuBundleId'] = ""
13572 kshitij.so 225
        data.append(val)
226
    return data
227
 
14005 amit.gupta 228
def getMerchantOrdersByUser(userId, page=1, window=50, searchMap={}):
229
    if searchMap is None:
230
        searchMap = {}
13603 amit.gupta 231
    if page==None:
232
        page = 1
233
 
234
    if window==None:
235
        window = 50
236
    result = {}
13582 amit.gupta 237
    skip = (page-1)*window
14005 amit.gupta 238
 
14353 amit.gupta 239
    if userId is not None:
240
        searchMap['userId'] = userId
13603 amit.gupta 241
    collection = get_mongo_connection().Dtr.merchantOrder
14609 amit.gupta 242
    cursor = collection.find(searchMap).sort("orderId",-1)
13603 amit.gupta 243
    total_count = cursor.count()
244
    pages = total_count/window + (0 if total_count%window==0 else 1)  
245
    print "total_count", total_count
246
    if total_count > skip:
13999 amit.gupta 247
        cursor = cursor.skip(skip).limit(window)
13603 amit.gupta 248
        orders = []
249
        for order in cursor:
14002 amit.gupta 250
            del(order["_id"])
251
            orders.append(order)
13603 amit.gupta 252
        result['data'] = orders
253
        result['window'] = window
254
        result['totalCount'] = total_count 
255
        result['currCount'] = cursor.count()
256
        result['totalPages'] = pages
257
        result['currPage'] = page    
258
        return result
259
    else:
260
        return result
13630 kshitij.so 261
 
13927 amit.gupta 262
def getRefunds(userId, page=1, window=10):
263
    if page==None:
264
        page = 1
265
 
266
    if window==None:
13995 amit.gupta 267
        window = 10
13927 amit.gupta 268
    result = {}
269
    skip = (page-1)*window
270
    collection = get_mongo_connection().Dtr.refund
271
    cursor = collection.find({"userId":userId})
272
    total_count = cursor.count()
273
    pages = total_count/window + (0 if total_count%window==0 else 1)  
274
    print "total_count", total_count
275
    if total_count > skip:
14668 amit.gupta 276
        cursor = cursor.skip(skip).limit(window).sort([('batch',-1)])
13927 amit.gupta 277
        refunds = []
278
        for refund in cursor:
279
            del(refund["_id"])
280
            refunds.append(refund)
281
        result['data'] = refunds
282
        result['window'] = window
283
        result['totalCount'] = total_count 
284
        result['currCount'] = cursor.count()
285
        result['totalPages'] = pages
286
        result['currPage'] = page    
287
        return result
288
    else:
289
        return result
290
 
291
def getPendingRefunds(userId):
13991 amit.gupta 292
    print type(userId)
13927 amit.gupta 293
    result = get_mongo_connection().Dtr.merchantOrder\
294
        .aggregate([
295
                    {'$match':{'subOrders.cashBackStatus':Store.CB_APPROVED, 'userId':userId}},
296
                    {'$unwind':"$subOrders"},
14670 amit.gupta 297
                    {'$match':{'subOrders.cashBackStatus':Store.CB_APPROVED}},
13927 amit.gupta 298
                    { 
299
                     '$group':{
300
                               '_id':None,
301
                               'amount': { '$sum':'$subOrders.cashBackAmount'},
302
                               }
303
                     }
13987 amit.gupta 304
                ])['result']
305
 
306
    if len(result)>0:
307
        result = result[0]        
308
        result.pop("_id")
309
    else:
310
        result={}
311
        result['amount'] = 0.0
14305 amit.gupta 312
    result['nextCredit'] = datetime.strftime(next_weekday(datetime.now(), int(PythonPropertyReader.getConfig('CREDIT_DAY_OF_WEEK'))),"%Y-%m-%d %H:%M:%S")
13927 amit.gupta 313
    return result
14037 kshitij.so 314
 
14671 amit.gupta 315
def getPendingCashbacks(userId):
316
    result = get_mongo_connection().Dtr.merchantOrder\
317
        .aggregate([
318
                    {'$match':{'subOrders.cashBackStatus':Store.CB_PENDING, 'userId':userId}},
319
                    {'$unwind':"$subOrders"},
320
                    {'$match':{'subOrders.cashBackStatus':Store.CB_PENDING}},
321
                    { 
322
                     '$group':{
323
                               '_id':None,
324
                               'amount': { '$sum':'$subOrders.cashBackAmount'},
325
                               }
326
                     }
327
                ])['result']
328
 
329
    if len(result)>0:
330
        result = result[0]        
331
        result.pop("_id")
332
    else:
333
        result={}
334
        result['amount'] = 0.0
335
    return result
336
 
14037 kshitij.so 337
def __populateCache(userId):
338
    print "Populating memcache for userId",userId
339
    outer_query = []
340
    outer_query.append({"showDeal":1})
341
    query = {}
15095 kshitij.so 342
    query['$gte'] = -100
14037 kshitij.so 343
    outer_query.append({'totalPoints':query})
344
    brandPrefMap = {}
345
    pricePrefMap = {}
346
    actionsMap = {}
347
    brand_p = session.query(price_preferences).filter_by(user_id=userId).all()
348
    for x in brand_p:
349
        pricePrefMap[x.category_id] = [x.min_price,x.max_price]
350
    for x in session.query(brand_preferences).filter_by(user_id=userId).all():
351
        temp_map = {}
352
        if brandPrefMap.has_key((x.brand).strip().upper()):
353
            val = brandPrefMap.get((x.brand).strip().upper())
354
            temp_map[x.category_id] = 1 if x.status == 'show' else 0
355
            val.append(temp_map)
356
        else:
357
            temp = []
358
            temp_map[x.category_id] = 1 if x.status == 'show' else 0
359
            temp.append(temp_map)
360
            brandPrefMap[(x.brand).strip().upper()] = temp
361
 
362
    for x in session.query(user_actions).filter_by(user_id=userId).all():
363
        actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0
15062 kshitij.so 364
    all_deals = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query},{'_id':1,'category_id':1,'brand':1,'totalPoints':1,'bestSellerPoints':1,'nlcPoints':1,'rank':1,'available_price':1,'dealType':1,'source_id':1,'brand_id':1}).sort([('totalPoints',pymongo.DESCENDING),('bestSellerPoints',pymongo.DESCENDING),('nlcPoints',pymongo.DESCENDING),('rank',pymongo.DESCENDING)]))
14037 kshitij.so 365
    all_category_deals = []
366
    mobile_deals = []
367
    tablet_deals = []
368
    for deal in all_deals:
369
        if actionsMap.get(deal['_id']) == 0:
370
            fav_weight =.25
371
        elif actionsMap.get(deal['_id']) == 1:
372
            fav_weight = 1.5
373
        else:
374
            fav_weight = 1
375
 
376
        if brandPrefMap.get(deal['brand'].strip().upper()) is not None:
377
            brand_weight = 1
378
            for brandInfo in brandPrefMap.get(deal['brand'].strip().upper()):
379
                if brandInfo.get(deal['category_id']) is not None:
380
                    if brandInfo.get(deal['category_id']) == 1:
14055 kshitij.so 381
                        brand_weight = 2.0
14037 kshitij.so 382
        else:
383
            brand_weight = 1
384
 
385
        if pricePrefMap.get(deal['category_id']) is not None:
386
 
387
            if deal['available_price'] >= pricePrefMap.get(deal['category_id'])[0] and deal['available_price'] <= pricePrefMap.get(deal['category_id'])[1]:
388
                asp_weight = 1.5
389
            elif  deal['available_price'] >= pricePrefMap.get(deal['category_id'])[0] - 0.5 * pricePrefMap.get(deal['category_id'])[0] and deal['available_price'] <= pricePrefMap.get(deal['category_id'])[1] + 0.5 * pricePrefMap.get(deal['category_id'])[1]:
390
                asp_weight = 1.2
391
            else:
392
                asp_weight = 1
393
        else:
394
            asp_weight = 1
395
 
396
        persPoints = deal['totalPoints'] * fav_weight * brand_weight * asp_weight
397
        deal['persPoints'] = persPoints
398
 
399
        if deal['category_id'] ==3:
400
            mobile_deals.append(deal)
401
        elif deal['category_id'] ==5:
402
            tablet_deals.append(deal)
403
        else:
404
            continue
405
        all_category_deals.append(deal)
406
 
14144 kshitij.so 407
    session.close()
14037 kshitij.so 408
    mem_cache_val = {3:mobile_deals, 5:tablet_deals, 0:all_deals}
409
    mc.set(str(userId), mem_cache_val)
410
 
411
 
14531 kshitij.so 412
def __populateFeaturedDeals():
413
    all_category_fd = []
414
    mobile_fd = []
415
    tablet_fd = []
14550 kshitij.so 416
    activeFeaturedDeals = get_mongo_connection().Catalog.FeaturedDeals.find({'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())}}).sort({'rank':pymongo.ASCENDING})
14531 kshitij.so 417
    for activeFeaturedDeal in activeFeaturedDeals:
418
        for k,v in activeFeaturedDeal['rankDetails']:
419
            featuredDeal = FeaturedDeals(activeFeaturedDeal['sku'], int(k), activeFeaturedDeal['thresholdPrice'], int(v))
420
            if featuredDeal.category_id == 0:
421
                all_category_fd.append(featuredDeal)
422
            elif featuredDeal.category_id == 3:
423
                mobile_fd.append(featuredDeal)
424
            elif featuredDeal.category_id == 5:
425
                tablet_fd.append(featuredDeal)
426
            else:
427
                continue
14550 kshitij.so 428
    mc.set("featured_deals_category_"+str(0), all_category_fd, 3600)
429
    mc.set("featured_deals_category_"+str(3), mobile_fd, 3600)
430
    mc.set("featured_deals_category_"+str(5), tablet_fd, 3600)
14037 kshitij.so 431
 
14791 kshitij.so 432
def getNewDeals(userId, category_id, offset, limit, sort, direction, filterData=None):
14761 kshitij.so 433
    if not bool(mc.get("category_cash_back")):
13921 kshitij.so 434
        populateCashBack()
14037 kshitij.so 435
 
14550 kshitij.so 436
    try:
437
        if mc.get("featured_deals_category_"+str(category_id)) is None:
438
            __populateFeaturedDeals()
439
    except:
440
        pass 
14531 kshitij.so 441
 
13771 kshitij.so 442
    rank = 1
14037 kshitij.so 443
    dealsMap = {}
444
    user_specific_deals = mc.get(str(userId))
445
    if user_specific_deals is None:
446
        __populateCache(userId)
447
        user_specific_deals = mc.get(str(userId))
14038 kshitij.so 448
    else:
449
        print "Getting user deals from cache"
14037 kshitij.so 450
    category_specific_deals = user_specific_deals.get(category_id)
451
 
452
    if sort is None or direction is None:
453
        sorted_deals = sorted(category_specific_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
454
    else:
455
        if sort == "bestSellerPoints":
456
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['bestSellerPoints'], x['rank'], x['nlcPoints']),reverse=True)
457
        else:
458
            if direction == -1:
459
                rev = True
460
            else:
461
                rev = False
462
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['available_price']),reverse=rev)
463
 
14791 kshitij.so 464
 
465
    print "============================"
466
    if filterData is not None:
467
        try:
468
            sorted_deals = filterDeals(sorted_deals, filterData)
469
        except:
15095 kshitij.so 470
            traceback.print_exc()    
14791 kshitij.so 471
 
14037 kshitij.so 472
    for d in sorted_deals[offset:offset+limit]:
473
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
474
        if not dealsMap.has_key(item[0]['identifier']):
475
            item[0]['dealRank'] = rank
476
            item[0]['persPoints'] = d['persPoints']
14322 kshitij.so 477
            if d['dealType'] == 1 and d['source_id'] ==1:
15040 kshitij.so 478
                item[0]['marketPlaceUrl'] = "http://www.amazon.in/dp/%s"%(item[0]['identifier'].strip())
479
            elif d['source_id'] ==3:
480
                item[0]['marketPlaceUrl'] = item[0]['marketPlaceUrl']+'?supc='+item[0].get('identifier')
481
            else:
482
                pass 
14037 kshitij.so 483
            try:
14761 kshitij.so 484
                cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
14037 kshitij.so 485
                if not cashBack or cashBack.get('cash_back_status')!=1:
486
                    item[0]['cash_back_type'] = 0
487
                    item[0]['cash_back'] = 0
488
                else:
14766 kshitij.so 489
                    item[0]['cash_back_type'] = int(cashBack['cash_back_type'])
14037 kshitij.so 490
                    item[0]['cash_back'] = cashBack['cash_back']
491
            except:
492
                print "Error in adding cashback to deals"
493
                item[0]['cash_back_type'] = 0
494
                item[0]['cash_back'] = 0
495
            dealsMap[item[0]['identifier']] = item[0]
496
 
497
            rank +=1
498
    return sorted(dealsMap.values(), key=itemgetter('dealRank'))
499
 
14791 kshitij.so 500
 
501
def filterDeals(deals, filterData):
502
    dealFiltered = []
503
    brandsFiltered = []
504
    filterArray = filterData.split('|')
505
    for data in filterArray:
506
        try:
507
            filter, info = data.split(':')
508
        except Exception as ex:
509
            traceback.print_exc()
510
            continue
511
        if filter == 'dealFilter':
512
            toFilter = info.split('^')
513
            print "deal filter ",toFilter
514
            if 'deals' in toFilter:
515
                dealFiltered = deals
516
                continue
517
            for filterVal in toFilter:
518
                if filterVal == 'dod':
519
                    for deal in deals:
520
                        if deal['dealType'] == 1:
521
                            dealFiltered.append(deal)
522
        elif filter == 'brandFilter':
523
            toFilter = info.split('^')
524
            print "brand filter ",toFilter
525
            if len(toFilter) == 0 or (len(toFilter)==1 and toFilter[0]==''):
526
                brandsFiltered = deals
527
            for deal in deals:
528
                if str(deal['brand_id']) in toFilter:
15150 kshitij.so 529
                    print "Adding ", deal
14791 kshitij.so 530
                    brandsFiltered.append(deal)
15040 kshitij.so 531
    if len(dealFiltered) == 0:
532
        return brandsFiltered
14791 kshitij.so 533
    return [i for i in dealFiltered for j in brandsFiltered if i['_id']==j['_id']]
534
 
535
 
14037 kshitij.so 536
def getDeals(userId, category_id, offset, limit, sort, direction):
14761 kshitij.so 537
    if not bool(mc.get("category_cash_back")):
14037 kshitij.so 538
        populateCashBack()
539
    rank = 1
13771 kshitij.so 540
    deals = {}
13910 kshitij.so 541
    outer_query = []
542
    outer_query.append({"showDeal":1})
543
    query = {}
544
    query['$gt'] = 0
545
    outer_query.append({'totalPoints':query})
546
    if category_id in (3,5):
547
        outer_query.append({'category_id':category_id})
13803 kshitij.so 548
    if sort is None or direction is None:
549
        direct = -1
13910 kshitij.so 550
        print outer_query
551
        data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('totalPoints',direct),('bestSellerPoints',direct),('nlcPoints',direct),('rank',direct)]).skip(offset).limit(limit))
13795 kshitij.so 552
    else:
13910 kshitij.so 553
        print outer_query
13803 kshitij.so 554
        direct = direction
13910 kshitij.so 555
        if sort == "bestSellerPoints":
556
            print "yes,sorting by bestSellerPoints"
557
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
558
        else:
559
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 560
    for d in data:
561
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
562
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 563
            item[0]['dealRank'] = rank
564
            try:
14761 kshitij.so 565
                cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
13921 kshitij.so 566
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 567
                    item[0]['cash_back_type'] = 0
568
                    item[0]['cash_back'] = 0
13921 kshitij.so 569
                else:
14766 kshitij.so 570
                    item[0]['cash_back_type'] = int(cashBack['cash_back_type'])
13928 kshitij.so 571
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 572
            except:
573
                print "Error in adding cashback to deals"
13928 kshitij.so 574
                item[0]['cash_back_type'] = 0
575
                item[0]['cash_back'] = 0
13771 kshitij.so 576
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 577
 
13771 kshitij.so 578
            rank +=1
13785 kshitij.so 579
    return sorted(deals.values(), key=itemgetter('dealRank'))
580
 
581
def getItem(skuId):
14761 kshitij.so 582
    if not bool(mc.get("category_cash_back")):
14113 kshitij.so 583
        populateCashBack()
13795 kshitij.so 584
    try:
585
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
14107 kshitij.so 586
        for sku in skuData:
587
            try:
14761 kshitij.so 588
                cashBack = getCashBack(sku['_id'], sku['source_id'], sku['category_id'])
14107 kshitij.so 589
                if not cashBack or cashBack.get('cash_back_status')!=1:
590
                    sku['cash_back_type'] = 0
591
                    sku['cash_back'] = 0
592
                else:
593
                    sku['cash_back_type'] = cashBack['cash_back_type']
594
                    sku['cash_back'] = cashBack['cash_back']
595
            except:
596
                print "Error in adding cashback to deals"
597
                sku['cash_back_type'] = 0
598
                sku['cash_back'] = 0
14629 kshitij.so 599
            sku['in_stock'] = int(sku['in_stock'])
600
            sku['is_shortage'] = int(sku['is_shortage'])
601
            sku['category_id'] = int(sku['category_id'])
602
            sku['status'] = int(sku['status'])
13785 kshitij.so 603
        return skuData
13795 kshitij.so 604
    except:
605
        return [{}]
13836 kshitij.so 606
 
14761 kshitij.so 607
def getCashBack(skuId, source_id, category_id):
608
    if not bool(mc.get("category_cash_back")):
609
        populateCashBack()
610
    itemCashBackMap = mc.get("item_cash_back")
13921 kshitij.so 611
    itemCashBack = itemCashBackMap.get(skuId)
612
    if itemCashBack is not None:
613
        return itemCashBack
14761 kshitij.so 614
    cashBackMap = mc.get("category_cash_back")
13921 kshitij.so 615
    sourceCashBack = cashBackMap.get(source_id)
616
    if sourceCashBack is not None and len(sourceCashBack) > 0:
617
        for cashBack in sourceCashBack:
618
            if cashBack.get(category_id) is None:
619
                continue
620
            else:
621
                return cashBack.get(category_id)
622
    else:
623
        return {}
624
 
15129 kshitij.so 625
def getDealRank(identifier, source_id, userId):
626
    if source_id in (1,2,4,5):
627
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
628
    elif source_id == 3:
629
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
630
    else:
15139 amit.gupta 631
        return {0:'No product found'}
15129 kshitij.so 632
    user_specific_deals = mc.get(str(userId))
633
    if user_specific_deals is None:
634
        __populateCache(userId)
635
        user_specific_deals = mc.get(str(userId))
636
    else:
637
        print "Getting user deals from cache"
638
    category_id = skuData[0]['category_id']
639
    category_specific_deals = user_specific_deals.get(category_id)
640
    if category_specific_deals is None or len(category_specific_deals) ==0:
15139 amit.gupta 641
        return {0:'Category specific deals is empty'}
15129 kshitij.so 642
    sorted_deals = sorted(category_specific_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
643
    rank = 1
644
    for sorted_deal in sorted_deals:
645
        if sorted_deal['_id'] == skuData[0]['_id']:
15140 amit.gupta 646
            return {rank:'Rank found'}
15129 kshitij.so 647
            break 
648
        rank+=1
15139 amit.gupta 649
    return {0:'Rank not found'}
15129 kshitij.so 650
 
651
 
13836 kshitij.so 652
def getCashBackDetails(identifier, source_id):
14761 kshitij.so 653
    if not bool(mc.get("category_cash_back")):
13921 kshitij.so 654
        populateCashBack()
655
 
13836 kshitij.so 656
    """Need to add item level cashback, no data available right now."""
13771 kshitij.so 657
 
13921 kshitij.so 658
    if source_id in (1,2,4,5):
13839 kshitij.so 659
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 660
    elif source_id == 3:
13839 kshitij.so 661
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 662
    else:
663
        return {}
13836 kshitij.so 664
    if len(skuData) > 0:
14761 kshitij.so 665
        itemCashBackMap = mc.get("item_cash_back")
13921 kshitij.so 666
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
667
        if itemCashBack is not None:
668
            return itemCashBack
14761 kshitij.so 669
        cashBackMap = mc.get("category_cash_back")
13921 kshitij.so 670
        sourceCashBack = cashBackMap.get(source_id)
671
        if sourceCashBack is not None and len(sourceCashBack) > 0:
672
            for cashBack in sourceCashBack:
673
                if cashBack.get(skuData[0]['category_id']) is None:
674
                    continue
675
                else:
676
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 677
        else:
678
            return {} 
679
    else:
680
        return {}
13986 amit.gupta 681
 
14398 amit.gupta 682
def getImgSrc(identifier, source_id):
683
    skuData = None
684
    if source_id in (1,2,4,5):
14414 amit.gupta 685
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'identifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 686
    elif source_id == 3:
14414 amit.gupta 687
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'secondaryIdentifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 688
    if skuData is None:
689
        return {}
690
    else:
691
        return {'thumbnail':skuData.get('thumbnail')}
13986 amit.gupta 692
 
693
def next_weekday(d, weekday):
694
    days_ahead = weekday - d.weekday()
695
    if days_ahead <= 0: # Target day already happened this week
696
        days_ahead += 7
697
    return d + timedelta(days_ahead)
698
 
13771 kshitij.so 699
 
13970 kshitij.so 700
def getAllDealerPrices(offset, limit):
701
    data = []
702
    collection = get_mongo_connection().Catalog.SkuDealerPrices
703
    cursor = collection.find().skip(offset).limit(limit)
704
    for val in cursor:
705
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
706
        if len(master) > 0:
14069 kshitij.so 707
            val['brand'] = master[0]['brand']
708
            val['source_product_name'] = master[0]['source_product_name']
709
            val['skuBundleId'] = master[0]['skuBundleId']
13970 kshitij.so 710
        else:
711
            val['brand'] = ""
712
            val['source_product_name'] = ""
713
            val['skuBundleId'] = ""
714
        data.append(val)
715
    return data
716
 
14553 kshitij.so 717
def addSkuDealerPrice(data, multi):
718
    if multi != 1:
719
        collection = get_mongo_connection().Catalog.SkuDealerPrices
720
        cursor = collection.find({"sku":data['sku']})
721
        if cursor.count() > 0:
722
            return {0:"Sku information already present."}
723
        else:
724
            collection.insert(data)
725
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
726
            return {1:"Data added successfully"}
13970 kshitij.so 727
    else:
14553 kshitij.so 728
        skuIds = __getBundledSkusfromSku(data['sku'])
729
        for sku in skuIds:
730
            data['sku'] = sku.get('_id')
731
            collection = get_mongo_connection().Catalog.SkuDealerPrices
732
            cursor = collection.find({"sku":data['sku']})
733
            if cursor.count() > 0:
734
                continue
735
            else:   
14558 kshitij.so 736
                data.pop('_id',None)
14553 kshitij.so 737
                collection.insert(data)
738
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13970 kshitij.so 739
        return {1:"Data added successfully"}
14553 kshitij.so 740
 
741
 
13970 kshitij.so 742
 
743
def updateSkuDealerPrice(data, _id):
744
    try:
745
        collection = get_mongo_connection().Catalog.SkuDealerPrices
746
        collection.update({'_id':ObjectId(_id)},{"$set":{'dp':data['dp']}},upsert=False, multi = False)
747
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
748
        return {1:"Data updated successfully"}
749
    except:
750
        return {0:"Data not updated."}
751
 
752
def updateExceptionalNlc(data, _id):
753
    try:
754
        collection = get_mongo_connection().Catalog.ExceptionalNlc
755
        collection.update({'_id':ObjectId(_id)},{"$set":{'maxNlc':data['maxNlc'], 'minNlc':data['minNlc'], 'overrideNlc':data['overrideNlc']}},upsert=False, multi = False)
756
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
757
        return {1:"Data updated successfully"}
758
    except:
759
        return {0:"Data not updated."}
760
 
14041 kshitij.so 761
def resetCache(userId):
14043 kshitij.so 762
    try:
763
        mc.delete(userId)
764
        return {1:'Cache cleared.'}
765
    except:
766
        return {0:'Unable to clear cache.'}
767
 
14575 kshitij.so 768
def updateCollection(data, multi):
14083 kshitij.so 769
    print data
14575 kshitij.so 770
    if multi!=1:
771
        try:
772
            collection = get_mongo_connection().Catalog[data['class']]
773
            class_name = data.pop('class')
774
            if class_name == "SkuSchemeDetails":
775
                data['addedOn'] = to_java_date(datetime.now())
776
            _id = data.pop('oid')
777
            result = collection.update({'_id':ObjectId(_id)},{"$set":data},upsert=False, multi = False)
15069 kshitij.so 778
            if class_name != "Notifications":
14852 kshitij.so 779
                record = list(collection.find({'_id':ObjectId(_id)}))
780
                if class_name !="CategoryDiscount":
781
                    get_mongo_connection().Catalog.MasterData.update({'_id':record[0]['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}})
782
                else:
783
                    get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
784
                                                                     {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
14575 kshitij.so 785
            return {1:"Data updated successfully"}
786
        except Exception as e:
787
            print e
788
            return {0:"Data not updated."}
789
    else:
790
        try:
791
            collection = get_mongo_connection().Catalog[data['class']]
792
            class_name = data.pop('class')
793
            _id = data.pop('oid')
794
            record = list(collection.find({'_id':ObjectId(_id)}))
795
            skuIds = __getBundledSkusfromSku(record[0]['sku'])
796
            for sku in skuIds:
797
                if class_name == "SkuSchemeDetails":
798
                    data['addedOn'] = to_java_date(datetime.now())
14582 kshitij.so 799
                data['sku'] = sku.get('_id')
14575 kshitij.so 800
                data.pop('_id',None)
14583 kshitij.so 801
                collection.update({'sku':sku.get('_id')},{"$set":data},upsert=False,multi=False)
14575 kshitij.so 802
            get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14580 kshitij.so 803
            return {1:"Data updatedsuccessfully"}
14575 kshitij.so 804
        except Exception as e:
805
            print e
806
            return {0:"Data not updated."}
807
 
14076 kshitij.so 808
 
14553 kshitij.so 809
def addNegativeDeals(data, multi):
810
    if multi !=1: 
811
        collection = get_mongo_connection().Catalog.NegativeDeals
812
        cursor = collection.find({"sku":data['sku']})
813
        if cursor.count() > 0:
814
            return {0:"Sku information already present."}
815
        else:
816
            collection.insert(data)
817
            return {1:"Data added successfully"}
14481 kshitij.so 818
    else:
14553 kshitij.so 819
        skuIds = __getBundledSkusfromSku(data['sku'])
820
        for sku in skuIds:
821
            data['sku'] = sku.get('_id')
822
            collection = get_mongo_connection().Catalog.NegativeDeals
823
            cursor = collection.find({"sku":data['sku']})
824
            if cursor.count() > 0:
825
                continue
826
            else:
14558 kshitij.so 827
                data.pop('_id',None)
14553 kshitij.so 828
                collection.insert(data)
14481 kshitij.so 829
        return {1:"Data added successfully"}
830
 
831
def getAllNegativeDeals(offset, limit):
832
    data = []
833
    collection = get_mongo_connection().Catalog.NegativeDeals
834
    cursor = collection.find().skip(offset).limit(limit)
835
    for val in cursor:
836
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
837
        if len(master) > 0:
838
            val['brand'] = master[0]['brand']
839
            val['source_product_name'] = master[0]['source_product_name']
840
            val['skuBundleId'] = master[0]['skuBundleId']
841
        else:
842
            val['brand'] = ""
843
            val['source_product_name'] = ""
844
            val['skuBundleId'] = ""
845
        data.append(val)
846
    return data
847
 
848
def getAllManualDeals(offset, limit):
849
    data = []
850
    collection = get_mongo_connection().Catalog.ManualDeals
15090 kshitij.so 851
    cursor = collection.find().skip(offset).limit(limit)
14481 kshitij.so 852
    for val in cursor:
853
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
854
        if len(master) > 0:
855
            val['brand'] = master[0]['brand']
856
            val['source_product_name'] = master[0]['source_product_name']
857
            val['skuBundleId'] = master[0]['skuBundleId']
858
        else:
859
            val['brand'] = ""
860
            val['source_product_name'] = ""
861
            val['skuBundleId'] = ""
862
        data.append(val)
863
    return data
14076 kshitij.so 864
 
14553 kshitij.so 865
def addManualDeal(data, multi):
866
    if multi !=1:
867
        collection = get_mongo_connection().Catalog.ManualDeals
15090 kshitij.so 868
        cursor = collection.find({'sku':data['sku']})
14553 kshitij.so 869
        if cursor.count() > 0:
870
            return {0:"Sku information already present."}
871
        else:
872
            collection.insert(data)
873
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
874
            return {1:"Data added successfully"}
14481 kshitij.so 875
    else:
14553 kshitij.so 876
        skuIds = __getBundledSkusfromSku(data['sku'])
877
        for sku in skuIds:
878
            data['sku'] = sku.get('_id')
879
            collection = get_mongo_connection().Catalog.ManualDeals
15090 kshitij.so 880
            cursor = collection.find({'sku':data['sku']})
14553 kshitij.so 881
            if cursor.count() > 0:
882
                continue
883
            else:
14558 kshitij.so 884
                data.pop('_id',None)
14553 kshitij.so 885
                collection.insert(data)
886
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14481 kshitij.so 887
        return {1:"Data added successfully"}
14553 kshitij.so 888
 
14481 kshitij.so 889
def deleteDocument(data):
890
    print data
891
    try:
892
        collection = get_mongo_connection().Catalog[data['class']]
893
        class_name = data.pop('class')
894
        _id = data.pop('oid')
895
        record = list(collection.find({'_id':ObjectId(_id)}))
896
        collection.remove({'_id':ObjectId(_id)})
15075 kshitij.so 897
        if class_name != "Notifications":
898
            if class_name !="CategoryDiscount":
899
                get_mongo_connection().Catalog.MasterData.update({'_id':record[0]['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}})
900
            else:
901
                get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
902
                                                                 {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
14481 kshitij.so 903
        return {1:"Document deleted successfully"}
904
    except Exception as e:
905
        print e
906
        return {0:"Document not deleted."}
13970 kshitij.so 907
 
14482 kshitij.so 908
def searchMaster(offset, limit, search_term):
909
    data = []
14531 kshitij.so 910
    if search_term is not None:
14551 kshitij.so 911
        terms = search_term.split(' ')
912
        outer_query = []
913
        for term in terms:
914
            outer_query.append({"source_product_name":re.compile(term, re.IGNORECASE)})
14531 kshitij.so 915
        try:
14551 kshitij.so 916
            collection = get_mongo_connection().Catalog.MasterData.find({"$and":outer_query,'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
14531 kshitij.so 917
            for record in collection:
918
                data.append(record)
919
        except:
920
            pass
921
    else:
922
        collection = get_mongo_connection().Catalog.MasterData.find({'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
14482 kshitij.so 923
        for record in collection:
924
            data.append(record)
925
    return data
14481 kshitij.so 926
 
14495 kshitij.so 927
def getAllFeaturedDeals(offset, limit):
928
    data = []
929
    collection = get_mongo_connection().Catalog.FeaturedDeals
930
    cursor = collection.find({'endDate':{'$gte':to_java_date(datetime.now())}}).skip(offset).limit(limit)
931
    for val in cursor:
932
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
933
        if len(master) > 0:
934
            val['brand'] = master[0]['brand']
935
            val['source_product_name'] = master[0]['source_product_name']
936
            val['skuBundleId'] = master[0]['skuBundleId']
937
        else:
938
            val['brand'] = ""
939
            val['source_product_name'] = ""
940
            val['skuBundleId'] = ""
941
        data.append(val)
942
    return data
943
 
14553 kshitij.so 944
def addFeaturedDeal(data, multi):
945
    if multi !=1:
946
        collection = get_mongo_connection().Catalog.FeaturedDeals
947
        cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
948
        if cursor.count() > 0:
949
            return {0:"Sku information already present."}
950
        else:
951
            collection.insert(data)
952
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
953
            return {1:"Data added successfully"}
14495 kshitij.so 954
    else:
14553 kshitij.so 955
        skuIds = __getBundledSkusfromSku(data['sku'])
956
        for sku in skuIds:
957
            data['sku'] = sku.get('_id')
958
            collection = get_mongo_connection().Catalog.FeaturedDeals
959
            cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
960
            if cursor.count() > 0:
961
                continue
962
            else:
14558 kshitij.so 963
                data.pop('_id',None)
14553 kshitij.so 964
                collection.insert(data)
965
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14495 kshitij.so 966
        return {1:"Data added successfully"}
967
 
14499 kshitij.so 968
def searchCollection(class_name, sku, skuBundleId):
14497 kshitij.so 969
    data = []
970
    collection = get_mongo_connection().Catalog[class_name]
15076 kshitij.so 971
    if class_name == "Notifications":
972
        cursor = collection.find({'skuBundleId':skuBundleId})
973
        for val in cursor:
974
            master = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':val['skuBundleId']}))
975
            if len(master) > 0:
976
                val['brand'] = master[0]['brand']
977
                val['model_name'] = master[0]['model_name']
978
                val['skuBundleId'] = master[0]['skuBundleId']
979
            else:
980
                val['brand'] = ""
981
                val['model_name'] = ""
982
                val['skuBundleId'] = val['skuBundleId']
983
            data.append(val)
15095 kshitij.so 984
        return data
14499 kshitij.so 985
    if sku is not None:
986
        cursor = collection.find({'sku':sku})
987
        for val in cursor:
988
            master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
989
            if len(master) > 0:
990
                val['brand'] = master[0]['brand']
991
                val['source_product_name'] = master[0]['source_product_name']
992
                val['skuBundleId'] = master[0]['skuBundleId']
993
            else:
994
                val['brand'] = ""
995
                val['source_product_name'] = ""
996
                val['skuBundleId'] = ""
997
            data.append(val)
998
        return data
999
    else:
14562 kshitij.so 1000
        skuIds = get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId}).distinct('_id')
14499 kshitij.so 1001
        for sku in skuIds:
1002
            cursor = collection.find({'sku':sku})
1003
            for val in cursor:
1004
                master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
1005
                if len(master) > 0:
1006
                    val['brand'] = master[0]['brand']
1007
                    val['source_product_name'] = master[0]['source_product_name']
1008
                    val['skuBundleId'] = master[0]['skuBundleId']
1009
                else:
1010
                    val['brand'] = ""
1011
                    val['source_product_name'] = ""
1012
                    val['skuBundleId'] = ""
1013
                data.append(val)
1014
        return data
14495 kshitij.so 1015
 
15074 kshitij.so 1016
def __getBrandIdForBrand(brandName, category_id):
1017
    brandInfo = Brands.query.filter(Brands.category_id==category_id).filter(Brands.name == brandName).all()
1018
    if brandInfo is None or len(brandInfo)!=1:
1019
        raise
1020
    else:
1021
        return brandInfo[0].id
1022
 
14588 kshitij.so 1023
def addNewItem(data):
14594 kshitij.so 1024
    try:
1025
        data['updatedOn'] = to_java_date(datetime.now())
1026
        data['addedOn'] = to_java_date(datetime.now())
1027
        data['priceUpdatedOn'] = to_java_date(datetime.now())
1028
        max_id = list(get_mongo_connection().Catalog.MasterData.find().sort([('_id',pymongo.DESCENDING)]).limit(1))
1029
        max_bundle = list(get_mongo_connection().Catalog.MasterData.find().sort([('skuBundleId',pymongo.DESCENDING)]).limit(1))
1030
        data['_id'] = max_id[0]['_id'] + 1
1031
        data['skuBundleId'] = max_bundle[0]['skuBundleId'] + 1
1032
        data['identifier'] = str(data['identifier'])
1033
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
15074 kshitij.so 1034
        data['brand_id'] = __getBrandIdForBrand(data['brand'], data['category_id'])
14594 kshitij.so 1035
        get_mongo_connection().Catalog.MasterData.insert(data)
1036
        return {1:'Data added successfully'}
1037
    except Exception as e:
1038
        print e
1039
        return {0:'Unable to add data.'}
15130 kshitij.so 1040
    finally:
1041
        session.close()
14588 kshitij.so 1042
 
1043
def addItemToExistingBundle(data):
1044
    try:
1045
        data['updatedOn'] = to_java_date(datetime.now())
1046
        data['addedOn'] = to_java_date(datetime.now())
1047
        data['priceUpdatedOn'] = to_java_date(datetime.now())
14593 kshitij.so 1048
        max_id = list(get_mongo_connection().Catalog.MasterData.find().sort([('_id',pymongo.DESCENDING)]).limit(1))
14590 kshitij.so 1049
        data['_id'] = max_id[0]['_id'] + 1
14594 kshitij.so 1050
        data['identifier'] = str(data['identifier'])
1051
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
15074 kshitij.so 1052
        data['brand_id'] = __getBrandIdForBrand(data['brand'], data['category_id'])
14588 kshitij.so 1053
        get_mongo_connection().Catalog.MasterData.insert(data)
1054
        return {1:'Data added successfully.'}
14594 kshitij.so 1055
    except Exception as e:
1056
        print e
14588 kshitij.so 1057
        return {0:'Unable to add data.'}
15130 kshitij.so 1058
    finally:
1059
        session.close()
14588 kshitij.so 1060
 
1061
def updateMaster(data, multi):
15130 kshitij.so 1062
    try:
1063
        print data
1064
        if multi != 1:
1065
            _id = data.pop('_id')
1066
            skuBundleId = data.pop('skuBundleId')
1067
            data['updatedOn'] = to_java_date(datetime.now())
1068
            data['identifier'] = str(data['identifier'])
1069
            data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
1070
            data['brand_id'] = __getBrandIdForBrand(data['brand'], data['category_id'])
1071
            get_mongo_connection().Catalog.MasterData.update({'_id':_id},{"$set":data},upsert=False)
1072
            return {1:'Data updated successfully.'}
1073
        else:
1074
            _id = data.pop('_id')
1075
            skuBundleId = data.pop('skuBundleId')
1076
            data['updatedOn'] = to_java_date(datetime.now())
1077
            data['identifier'] = str(data['identifier'])
1078
            data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
1079
            data['brand_id'] = __getBrandIdForBrand(data['brand'], data['category_id'])
1080
            get_mongo_connection().Catalog.MasterData.update({'_id':_id},{"$set":data},upsert=False)
1081
            similarItems = get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId})
1082
            for item in similarItems:
1083
                if item['_id'] == _id:
1084
                    continue
1085
                item['updatedOn'] = to_java_date(datetime.now())
1086
                item['thumbnail'] = data['thumbnail']
1087
                item['category'] = data['category']
1088
                item['category_id'] = data['category_id']
1089
                item['tagline'] = data['tagline']
1090
                item['is_shortage'] = data['is_shortage']
1091
                item['mrp'] = data['mrp']
1092
                item['status'] = data['status']
1093
                item['maxPrice'] = data['maxPrice']
1094
                item['brand_id'] = data['brand_id']
1095
                similar_item_id = item.pop('_id')
1096
                get_mongo_connection().Catalog.MasterData.update({'_id':similar_item_id},{"$set":item},upsert=False)
1097
            return {1:'Data updated successfully.'}
1098
    finally:
1099
        session.close()
14619 kshitij.so 1100
 
1101
def getLiveCricScore():
1102
    return mc.get('liveScore')
14852 kshitij.so 1103
 
1104
def addBundleToNotification(data):
1105
    try:
15069 kshitij.so 1106
        collection = get_mongo_connection().Catalog.Notifications
14852 kshitij.so 1107
        cursor = collection.find({'skuBundleId':data['skuBundleId']})
1108
        if cursor.count() > 0:
1109
            return {0:"SkuBundleId information already present."}
1110
        else:
1111
            collection.insert(data)
1112
            return {1:'Data updated successfully.'}
1113
    except:
1114
        return {0:'Unable to add data.'}
1115
 
1116
def getAllNotifications(offset, limit):
1117
    data = []
15069 kshitij.so 1118
    collection = get_mongo_connection().Catalog.Notifications
14852 kshitij.so 1119
    cursor = collection.find().skip(offset).limit(limit)
1120
    for val in cursor:
15072 kshitij.so 1121
        master = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':val['skuBundleId']}))
14852 kshitij.so 1122
        if len(master) > 0:
1123
            val['brand'] = master[0]['brand']
15071 kshitij.so 1124
            val['model_name'] = master[0]['model_name']
14852 kshitij.so 1125
            val['skuBundleId'] = master[0]['skuBundleId']
1126
        else:
1127
            val['brand'] = ""
15071 kshitij.so 1128
            val['model_name'] = ""
1129
            val['skuBundleId'] = val['skuBundleId']
14852 kshitij.so 1130
        data.append(val)
1131
    return data
14997 kshitij.so 1132
 
1133
def getBrandsForFilter(category_id):
1134
    if mc.get("brandFilter") is None:
15095 kshitij.so 1135
        print "Populating brand data for category_id %d" %(category_id)
14997 kshitij.so 1136
        tabData, mobData = [], []
1137
        mobileDeals = get_mongo_connection().Catalog.Deals.aggregate([
15095 kshitij.so 1138
                                                                      {"$match":{"category_id":3,"showDeal":1,"totalPoints":{"$gte":-100}}
14997 kshitij.so 1139
                                                                    },
1140
                                                                 {"$group" : 
1141
                                                                  {'_id':{'brand_id':'$brand_id','brand':'$brand'},'count':{'$sum':1}}
1142
                                                                  }
1143
                                                                ])
14588 kshitij.so 1144
 
14997 kshitij.so 1145
        tabletDeals = get_mongo_connection().Catalog.Deals.aggregate([
15095 kshitij.so 1146
                                                                      {"$match":{"category_id":5,"showDeal":1,"totalPoints":{"$gte":-100}}
14997 kshitij.so 1147
                                                                    },
1148
                                                                 {"$group" : 
1149
                                                                  {'_id':{'brand_id':'$brand_id','brand':'$brand'},'count':{'$sum':1}}
1150
                                                                  }
1151
                                                                ])
1152
 
1153
        allDeals = get_mongo_connection().Catalog.Deals.aggregate([
15095 kshitij.so 1154
                                                                   {"$match":{"showDeal":1,"totalPoints":{"$gte":-100}}
14997 kshitij.so 1155
                                                                    },
1156
                                                                 {"$group" : 
1157
                                                                  {'_id':{'brand_id':'$brand_id','brand':'$brand'},'count':{'$sum':1}}
1158
                                                                  }
1159
                                                                ])
1160
        #print mobileDeals
1161
        #print "==========Mobile data ends=========="
1162
 
1163
        #print tabletDeals
1164
        #print "==========Tablet data ends=========="
1165
 
1166
        #print allDeals
1167
        #print "==========All deal data ends========="
1168
 
1169
        for mobileDeal in mobileDeals['result']:
1170
            if mobileDeal.get('_id').get('brand_id') != 0:
1171
                tempMap = {}
1172
                tempMap['brand'] = mobileDeal.get('_id').get('brand')
1173
                tempMap['brand_id'] = mobileDeal.get('_id').get('brand_id')
1174
                tempMap['count'] = mobileDeal.get('count')
1175
                mobData.append(tempMap)
1176
 
1177
        for tabletDeal in tabletDeals['result']:
1178
            if tabletDeal.get('_id').get('brand_id') != 0:
1179
                tempMap = {}
1180
                tempMap['brand'] = tabletDeal.get('_id').get('brand')
1181
                tempMap['brand_id'] = tabletDeal.get('_id').get('brand_id')
1182
                tempMap['count'] = tabletDeal.get('count')
1183
                tabData.append(tempMap)
1184
 
1185
 
1186
        brandMap = {}
1187
        for allDeal in allDeals['result']:
1188
            if allDeal.get('_id').get('brand_id') != 0:
1189
                if brandMap.has_key(allDeal.get('_id').get('brand')):
15002 kshitij.so 1190
                    brand_ids = brandMap.get(allDeal.get('_id').get('brand')).get('brand_ids')
14997 kshitij.so 1191
                    brand_ids.append(allDeal.get('_id').get('brand_id'))
15003 kshitij.so 1192
                    brandMap[allDeal.get('_id').get('brand')] = {'brand_ids':brand_ids,'count':brandMap.get(allDeal.get('_id').get('brand')).get('count') + allDeal.get('count')}
14997 kshitij.so 1193
                else:
1194
                    temp = []
1195
                    temp.append(allDeal.get('_id').get('brand_id'))
15002 kshitij.so 1196
                    brandMap[allDeal.get('_id').get('brand')] = {'brand_ids':temp,'count':allDeal.get('count')}
14997 kshitij.so 1197
 
1198
        mc.set("brandFilter",{0:brandMap, 3:mobData, 5:tabData}, 600)  
1199
 
15062 kshitij.so 1200
    return sorted(mc.get("brandFilter").get(category_id), key = lambda x: (-x['count'], x['brand']))
14997 kshitij.so 1201
 
13572 kshitij.so 1202
def main():
15150 kshitij.so 1203
    getNewDeals(47, 3, 0, 20, None, None, "brandFilter:64")
13811 kshitij.so 1204
 
13921 kshitij.so 1205
 
13572 kshitij.so 1206
if __name__=='__main__':
13932 amit.gupta 1207
    main()