Subversion Repositories SmartDukaan

Rev

Rev 14852 | Rev 15002 | 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, \
14305 amit.gupta 8
    user_actions
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 = {}
342
    query['$gt'] = 0
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
14323 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}).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:
470
            print traceback.print_exc()    
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:
478
                item[0]['marketPlaceUrl'] = "http://www.amazon.in/dp/%s"%(item[0]['identifier'].strip()) 
14037 kshitij.so 479
            try:
14761 kshitij.so 480
                cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
14037 kshitij.so 481
                if not cashBack or cashBack.get('cash_back_status')!=1:
482
                    item[0]['cash_back_type'] = 0
483
                    item[0]['cash_back'] = 0
484
                else:
14766 kshitij.so 485
                    item[0]['cash_back_type'] = int(cashBack['cash_back_type'])
14037 kshitij.so 486
                    item[0]['cash_back'] = cashBack['cash_back']
487
            except:
488
                print "Error in adding cashback to deals"
489
                item[0]['cash_back_type'] = 0
490
                item[0]['cash_back'] = 0
491
            dealsMap[item[0]['identifier']] = item[0]
492
 
493
            rank +=1
494
    return sorted(dealsMap.values(), key=itemgetter('dealRank'))
495
 
14791 kshitij.so 496
 
497
def filterDeals(deals, filterData):
498
    dealFiltered = []
499
    brandsFiltered = []
500
    filterArray = filterData.split('|')
501
    for data in filterArray:
502
        try:
503
            filter, info = data.split(':')
504
        except Exception as ex:
505
            traceback.print_exc()
506
            continue
507
        if filter == 'dealFilter':
508
            toFilter = info.split('^')
509
            print "deal filter ",toFilter
510
            if 'deals' in toFilter:
511
                dealFiltered = deals
512
                continue
513
            for filterVal in toFilter:
514
                if filterVal == 'dod':
515
                    for deal in deals:
516
                        if deal['dealType'] == 1:
517
                            dealFiltered.append(deal)
518
        elif filter == 'brandFilter':
519
            toFilter = info.split('^')
520
            print "brand filter ",toFilter
521
            if len(toFilter) == 0 or (len(toFilter)==1 and toFilter[0]==''):
522
                brandsFiltered = deals
523
            for deal in deals:
524
                if str(deal['brand_id']) in toFilter:
525
                    brandsFiltered.append(deal)
526
    return [i for i in dealFiltered for j in brandsFiltered if i['_id']==j['_id']]
527
 
528
 
14037 kshitij.so 529
def getDeals(userId, category_id, offset, limit, sort, direction):
14761 kshitij.so 530
    if not bool(mc.get("category_cash_back")):
14037 kshitij.so 531
        populateCashBack()
532
    rank = 1
13771 kshitij.so 533
    deals = {}
13910 kshitij.so 534
    outer_query = []
535
    outer_query.append({"showDeal":1})
536
    query = {}
537
    query['$gt'] = 0
538
    outer_query.append({'totalPoints':query})
539
    if category_id in (3,5):
540
        outer_query.append({'category_id':category_id})
13803 kshitij.so 541
    if sort is None or direction is None:
542
        direct = -1
13910 kshitij.so 543
        print outer_query
544
        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 545
    else:
13910 kshitij.so 546
        print outer_query
13803 kshitij.so 547
        direct = direction
13910 kshitij.so 548
        if sort == "bestSellerPoints":
549
            print "yes,sorting by bestSellerPoints"
550
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
551
        else:
552
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 553
    for d in data:
554
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
555
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 556
            item[0]['dealRank'] = rank
557
            try:
14761 kshitij.so 558
                cashBack = getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
13921 kshitij.so 559
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 560
                    item[0]['cash_back_type'] = 0
561
                    item[0]['cash_back'] = 0
13921 kshitij.so 562
                else:
14766 kshitij.so 563
                    item[0]['cash_back_type'] = int(cashBack['cash_back_type'])
13928 kshitij.so 564
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 565
            except:
566
                print "Error in adding cashback to deals"
13928 kshitij.so 567
                item[0]['cash_back_type'] = 0
568
                item[0]['cash_back'] = 0
13771 kshitij.so 569
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 570
 
13771 kshitij.so 571
            rank +=1
13785 kshitij.so 572
    return sorted(deals.values(), key=itemgetter('dealRank'))
573
 
574
def getItem(skuId):
14761 kshitij.so 575
    if not bool(mc.get("category_cash_back")):
14113 kshitij.so 576
        populateCashBack()
13795 kshitij.so 577
    try:
578
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
14107 kshitij.so 579
        for sku in skuData:
580
            try:
14761 kshitij.so 581
                cashBack = getCashBack(sku['_id'], sku['source_id'], sku['category_id'])
14107 kshitij.so 582
                if not cashBack or cashBack.get('cash_back_status')!=1:
583
                    sku['cash_back_type'] = 0
584
                    sku['cash_back'] = 0
585
                else:
586
                    sku['cash_back_type'] = cashBack['cash_back_type']
587
                    sku['cash_back'] = cashBack['cash_back']
588
            except:
589
                print "Error in adding cashback to deals"
590
                sku['cash_back_type'] = 0
591
                sku['cash_back'] = 0
14629 kshitij.so 592
            sku['in_stock'] = int(sku['in_stock'])
593
            sku['is_shortage'] = int(sku['is_shortage'])
594
            sku['category_id'] = int(sku['category_id'])
595
            sku['status'] = int(sku['status'])
13785 kshitij.so 596
        return skuData
13795 kshitij.so 597
    except:
598
        return [{}]
13836 kshitij.so 599
 
14761 kshitij.so 600
def getCashBack(skuId, source_id, category_id):
601
    if not bool(mc.get("category_cash_back")):
602
        populateCashBack()
603
    itemCashBackMap = mc.get("item_cash_back")
13921 kshitij.so 604
    itemCashBack = itemCashBackMap.get(skuId)
605
    if itemCashBack is not None:
606
        return itemCashBack
14761 kshitij.so 607
    cashBackMap = mc.get("category_cash_back")
13921 kshitij.so 608
    sourceCashBack = cashBackMap.get(source_id)
609
    if sourceCashBack is not None and len(sourceCashBack) > 0:
610
        for cashBack in sourceCashBack:
611
            if cashBack.get(category_id) is None:
612
                continue
613
            else:
614
                return cashBack.get(category_id)
615
    else:
616
        return {}
617
 
13836 kshitij.so 618
def getCashBackDetails(identifier, source_id):
14761 kshitij.so 619
    if not bool(mc.get("category_cash_back")):
13921 kshitij.so 620
        populateCashBack()
621
 
13836 kshitij.so 622
    """Need to add item level cashback, no data available right now."""
13771 kshitij.so 623
 
13921 kshitij.so 624
    if source_id in (1,2,4,5):
13839 kshitij.so 625
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 626
    elif source_id == 3:
13839 kshitij.so 627
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 628
    else:
629
        return {}
13836 kshitij.so 630
    if len(skuData) > 0:
14761 kshitij.so 631
        itemCashBackMap = mc.get("item_cash_back")
13921 kshitij.so 632
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
633
        if itemCashBack is not None:
634
            return itemCashBack
14761 kshitij.so 635
        cashBackMap = mc.get("category_cash_back")
13921 kshitij.so 636
        sourceCashBack = cashBackMap.get(source_id)
637
        if sourceCashBack is not None and len(sourceCashBack) > 0:
638
            for cashBack in sourceCashBack:
639
                if cashBack.get(skuData[0]['category_id']) is None:
640
                    continue
641
                else:
642
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 643
        else:
644
            return {} 
645
    else:
646
        return {}
13986 amit.gupta 647
 
14398 amit.gupta 648
def getImgSrc(identifier, source_id):
649
    skuData = None
650
    if source_id in (1,2,4,5):
14414 amit.gupta 651
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'identifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 652
    elif source_id == 3:
14414 amit.gupta 653
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'secondaryIdentifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 654
    if skuData is None:
655
        return {}
656
    else:
657
        return {'thumbnail':skuData.get('thumbnail')}
13986 amit.gupta 658
 
659
def next_weekday(d, weekday):
660
    days_ahead = weekday - d.weekday()
661
    if days_ahead <= 0: # Target day already happened this week
662
        days_ahead += 7
663
    return d + timedelta(days_ahead)
664
 
13771 kshitij.so 665
 
13970 kshitij.so 666
def getAllDealerPrices(offset, limit):
667
    data = []
668
    collection = get_mongo_connection().Catalog.SkuDealerPrices
669
    cursor = collection.find().skip(offset).limit(limit)
670
    for val in cursor:
671
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
672
        if len(master) > 0:
14069 kshitij.so 673
            val['brand'] = master[0]['brand']
674
            val['source_product_name'] = master[0]['source_product_name']
675
            val['skuBundleId'] = master[0]['skuBundleId']
13970 kshitij.so 676
        else:
677
            val['brand'] = ""
678
            val['source_product_name'] = ""
679
            val['skuBundleId'] = ""
680
        data.append(val)
681
    return data
682
 
14553 kshitij.so 683
def addSkuDealerPrice(data, multi):
684
    if multi != 1:
685
        collection = get_mongo_connection().Catalog.SkuDealerPrices
686
        cursor = collection.find({"sku":data['sku']})
687
        if cursor.count() > 0:
688
            return {0:"Sku information already present."}
689
        else:
690
            collection.insert(data)
691
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
692
            return {1:"Data added successfully"}
13970 kshitij.so 693
    else:
14553 kshitij.so 694
        skuIds = __getBundledSkusfromSku(data['sku'])
695
        for sku in skuIds:
696
            data['sku'] = sku.get('_id')
697
            collection = get_mongo_connection().Catalog.SkuDealerPrices
698
            cursor = collection.find({"sku":data['sku']})
699
            if cursor.count() > 0:
700
                continue
701
            else:   
14558 kshitij.so 702
                data.pop('_id',None)
14553 kshitij.so 703
                collection.insert(data)
704
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13970 kshitij.so 705
        return {1:"Data added successfully"}
14553 kshitij.so 706
 
707
 
13970 kshitij.so 708
 
709
def updateSkuDealerPrice(data, _id):
710
    try:
711
        collection = get_mongo_connection().Catalog.SkuDealerPrices
712
        collection.update({'_id':ObjectId(_id)},{"$set":{'dp':data['dp']}},upsert=False, multi = False)
713
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
714
        return {1:"Data updated successfully"}
715
    except:
716
        return {0:"Data not updated."}
717
 
718
def updateExceptionalNlc(data, _id):
719
    try:
720
        collection = get_mongo_connection().Catalog.ExceptionalNlc
721
        collection.update({'_id':ObjectId(_id)},{"$set":{'maxNlc':data['maxNlc'], 'minNlc':data['minNlc'], 'overrideNlc':data['overrideNlc']}},upsert=False, multi = False)
722
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
723
        return {1:"Data updated successfully"}
724
    except:
725
        return {0:"Data not updated."}
726
 
14041 kshitij.so 727
def resetCache(userId):
14043 kshitij.so 728
    try:
729
        mc.delete(userId)
730
        return {1:'Cache cleared.'}
731
    except:
732
        return {0:'Unable to clear cache.'}
733
 
14575 kshitij.so 734
def updateCollection(data, multi):
14083 kshitij.so 735
    print data
14575 kshitij.so 736
    if multi!=1:
737
        try:
738
            collection = get_mongo_connection().Catalog[data['class']]
739
            class_name = data.pop('class')
740
            if class_name == "SkuSchemeDetails":
741
                data['addedOn'] = to_java_date(datetime.now())
742
            _id = data.pop('oid')
743
            result = collection.update({'_id':ObjectId(_id)},{"$set":data},upsert=False, multi = False)
14852 kshitij.so 744
            if class_name != "Notification":
745
                record = list(collection.find({'_id':ObjectId(_id)}))
746
                if class_name !="CategoryDiscount":
747
                    get_mongo_connection().Catalog.MasterData.update({'_id':record[0]['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}})
748
                else:
749
                    get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
750
                                                                     {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
14575 kshitij.so 751
            return {1:"Data updated successfully"}
752
        except Exception as e:
753
            print e
754
            return {0:"Data not updated."}
755
    else:
756
        try:
757
            collection = get_mongo_connection().Catalog[data['class']]
758
            class_name = data.pop('class')
759
            _id = data.pop('oid')
760
            record = list(collection.find({'_id':ObjectId(_id)}))
761
            skuIds = __getBundledSkusfromSku(record[0]['sku'])
762
            for sku in skuIds:
763
                if class_name == "SkuSchemeDetails":
764
                    data['addedOn'] = to_java_date(datetime.now())
14582 kshitij.so 765
                data['sku'] = sku.get('_id')
14575 kshitij.so 766
                data.pop('_id',None)
14583 kshitij.so 767
                collection.update({'sku':sku.get('_id')},{"$set":data},upsert=False,multi=False)
14575 kshitij.so 768
            get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14580 kshitij.so 769
            return {1:"Data updatedsuccessfully"}
14575 kshitij.so 770
        except Exception as e:
771
            print e
772
            return {0:"Data not updated."}
773
 
14076 kshitij.so 774
 
14553 kshitij.so 775
def addNegativeDeals(data, multi):
776
    if multi !=1: 
777
        collection = get_mongo_connection().Catalog.NegativeDeals
778
        cursor = collection.find({"sku":data['sku']})
779
        if cursor.count() > 0:
780
            return {0:"Sku information already present."}
781
        else:
782
            collection.insert(data)
783
            return {1:"Data added successfully"}
14481 kshitij.so 784
    else:
14553 kshitij.so 785
        skuIds = __getBundledSkusfromSku(data['sku'])
786
        for sku in skuIds:
787
            data['sku'] = sku.get('_id')
788
            collection = get_mongo_connection().Catalog.NegativeDeals
789
            cursor = collection.find({"sku":data['sku']})
790
            if cursor.count() > 0:
791
                continue
792
            else:
14558 kshitij.so 793
                data.pop('_id',None)
14553 kshitij.so 794
                collection.insert(data)
14481 kshitij.so 795
        return {1:"Data added successfully"}
796
 
797
def getAllNegativeDeals(offset, limit):
798
    data = []
799
    collection = get_mongo_connection().Catalog.NegativeDeals
800
    cursor = collection.find().skip(offset).limit(limit)
801
    for val in cursor:
802
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
803
        if len(master) > 0:
804
            val['brand'] = master[0]['brand']
805
            val['source_product_name'] = master[0]['source_product_name']
806
            val['skuBundleId'] = master[0]['skuBundleId']
807
        else:
808
            val['brand'] = ""
809
            val['source_product_name'] = ""
810
            val['skuBundleId'] = ""
811
        data.append(val)
812
    return data
813
 
814
def getAllManualDeals(offset, limit):
815
    data = []
816
    collection = get_mongo_connection().Catalog.ManualDeals
14495 kshitij.so 817
    cursor = collection.find({'endDate':{'$gte':to_java_date(datetime.now())}}).skip(offset).limit(limit)
14481 kshitij.so 818
    for val in cursor:
819
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
820
        if len(master) > 0:
821
            val['brand'] = master[0]['brand']
822
            val['source_product_name'] = master[0]['source_product_name']
823
            val['skuBundleId'] = master[0]['skuBundleId']
824
        else:
825
            val['brand'] = ""
826
            val['source_product_name'] = ""
827
            val['skuBundleId'] = ""
828
        data.append(val)
829
    return data
14076 kshitij.so 830
 
14553 kshitij.so 831
def addManualDeal(data, multi):
832
    if multi !=1:
833
        collection = get_mongo_connection().Catalog.ManualDeals
834
        cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
835
        if cursor.count() > 0:
836
            return {0:"Sku information already present."}
837
        else:
838
            collection.insert(data)
839
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
840
            return {1:"Data added successfully"}
14481 kshitij.so 841
    else:
14553 kshitij.so 842
        skuIds = __getBundledSkusfromSku(data['sku'])
843
        for sku in skuIds:
844
            data['sku'] = sku.get('_id')
845
            collection = get_mongo_connection().Catalog.ManualDeals
846
            cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
847
            if cursor.count() > 0:
848
                continue
849
            else:
14558 kshitij.so 850
                data.pop('_id',None)
14553 kshitij.so 851
                collection.insert(data)
852
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14481 kshitij.so 853
        return {1:"Data added successfully"}
14553 kshitij.so 854
 
14481 kshitij.so 855
def deleteDocument(data):
856
    print data
857
    try:
858
        collection = get_mongo_connection().Catalog[data['class']]
859
        class_name = data.pop('class')
860
        _id = data.pop('oid')
861
        record = list(collection.find({'_id':ObjectId(_id)}))
862
        collection.remove({'_id':ObjectId(_id)})
863
        if class_name !="CategoryDiscount":
864
            get_mongo_connection().Catalog.MasterData.update({'_id':record[0]['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}})
865
        else:
866
            get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
867
                                                             {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
868
        return {1:"Document deleted successfully"}
869
    except Exception as e:
870
        print e
871
        return {0:"Document not deleted."}
13970 kshitij.so 872
 
14482 kshitij.so 873
def searchMaster(offset, limit, search_term):
874
    data = []
14531 kshitij.so 875
    if search_term is not None:
14551 kshitij.so 876
        terms = search_term.split(' ')
877
        outer_query = []
878
        for term in terms:
879
            outer_query.append({"source_product_name":re.compile(term, re.IGNORECASE)})
14531 kshitij.so 880
        try:
14551 kshitij.so 881
            collection = get_mongo_connection().Catalog.MasterData.find({"$and":outer_query,'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
14531 kshitij.so 882
            for record in collection:
883
                data.append(record)
884
        except:
885
            pass
886
    else:
887
        collection = get_mongo_connection().Catalog.MasterData.find({'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
14482 kshitij.so 888
        for record in collection:
889
            data.append(record)
890
    return data
14481 kshitij.so 891
 
14495 kshitij.so 892
def getAllFeaturedDeals(offset, limit):
893
    data = []
894
    collection = get_mongo_connection().Catalog.FeaturedDeals
895
    cursor = collection.find({'endDate':{'$gte':to_java_date(datetime.now())}}).skip(offset).limit(limit)
896
    for val in cursor:
897
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
898
        if len(master) > 0:
899
            val['brand'] = master[0]['brand']
900
            val['source_product_name'] = master[0]['source_product_name']
901
            val['skuBundleId'] = master[0]['skuBundleId']
902
        else:
903
            val['brand'] = ""
904
            val['source_product_name'] = ""
905
            val['skuBundleId'] = ""
906
        data.append(val)
907
    return data
908
 
14553 kshitij.so 909
def addFeaturedDeal(data, multi):
910
    if multi !=1:
911
        collection = get_mongo_connection().Catalog.FeaturedDeals
912
        cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
913
        if cursor.count() > 0:
914
            return {0:"Sku information already present."}
915
        else:
916
            collection.insert(data)
917
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
918
            return {1:"Data added successfully"}
14495 kshitij.so 919
    else:
14553 kshitij.so 920
        skuIds = __getBundledSkusfromSku(data['sku'])
921
        for sku in skuIds:
922
            data['sku'] = sku.get('_id')
923
            collection = get_mongo_connection().Catalog.FeaturedDeals
924
            cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
925
            if cursor.count() > 0:
926
                continue
927
            else:
14558 kshitij.so 928
                data.pop('_id',None)
14553 kshitij.so 929
                collection.insert(data)
930
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14495 kshitij.so 931
        return {1:"Data added successfully"}
932
 
14499 kshitij.so 933
def searchCollection(class_name, sku, skuBundleId):
14497 kshitij.so 934
    data = []
935
    collection = get_mongo_connection().Catalog[class_name]
14499 kshitij.so 936
    if sku is not None:
937
        cursor = collection.find({'sku':sku})
938
        for val in cursor:
939
            master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
940
            if len(master) > 0:
941
                val['brand'] = master[0]['brand']
942
                val['source_product_name'] = master[0]['source_product_name']
943
                val['skuBundleId'] = master[0]['skuBundleId']
944
            else:
945
                val['brand'] = ""
946
                val['source_product_name'] = ""
947
                val['skuBundleId'] = ""
948
            data.append(val)
949
        return data
950
    else:
14562 kshitij.so 951
        skuIds = get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId}).distinct('_id')
14499 kshitij.so 952
        for sku in skuIds:
953
            cursor = collection.find({'sku':sku})
954
            for val in cursor:
955
                master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
956
                if len(master) > 0:
957
                    val['brand'] = master[0]['brand']
958
                    val['source_product_name'] = master[0]['source_product_name']
959
                    val['skuBundleId'] = master[0]['skuBundleId']
960
                else:
961
                    val['brand'] = ""
962
                    val['source_product_name'] = ""
963
                    val['skuBundleId'] = ""
964
                data.append(val)
965
        return data
14495 kshitij.so 966
 
14588 kshitij.so 967
def addNewItem(data):
14594 kshitij.so 968
    try:
969
        data['updatedOn'] = to_java_date(datetime.now())
970
        data['addedOn'] = to_java_date(datetime.now())
971
        data['priceUpdatedOn'] = to_java_date(datetime.now())
972
        max_id = list(get_mongo_connection().Catalog.MasterData.find().sort([('_id',pymongo.DESCENDING)]).limit(1))
973
        max_bundle = list(get_mongo_connection().Catalog.MasterData.find().sort([('skuBundleId',pymongo.DESCENDING)]).limit(1))
974
        data['_id'] = max_id[0]['_id'] + 1
975
        data['skuBundleId'] = max_bundle[0]['skuBundleId'] + 1
976
        data['identifier'] = str(data['identifier'])
977
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
978
        get_mongo_connection().Catalog.MasterData.insert(data)
979
        return {1:'Data added successfully'}
980
    except Exception as e:
981
        print e
982
        return {0:'Unable to add data.'}
14588 kshitij.so 983
 
984
def addItemToExistingBundle(data):
985
    try:
986
        data['updatedOn'] = to_java_date(datetime.now())
987
        data['addedOn'] = to_java_date(datetime.now())
988
        data['priceUpdatedOn'] = to_java_date(datetime.now())
14593 kshitij.so 989
        max_id = list(get_mongo_connection().Catalog.MasterData.find().sort([('_id',pymongo.DESCENDING)]).limit(1))
14590 kshitij.so 990
        data['_id'] = max_id[0]['_id'] + 1
14594 kshitij.so 991
        data['identifier'] = str(data['identifier'])
992
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
14588 kshitij.so 993
        get_mongo_connection().Catalog.MasterData.insert(data)
994
        return {1:'Data added successfully.'}
14594 kshitij.so 995
    except Exception as e:
996
        print e
14588 kshitij.so 997
        return {0:'Unable to add data.'}
998
 
999
def updateMaster(data, multi):
14640 kshitij.so 1000
    print data
14597 kshitij.so 1001
    if multi != 1:
1002
        _id = data.pop('_id')
1003
        skuBundleId = data.pop('skuBundleId')
1004
        data['updatedOn'] = to_java_date(datetime.now())
14640 kshitij.so 1005
        data['identifier'] = str(data['identifier'])
1006
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
14597 kshitij.so 1007
        get_mongo_connection().Catalog.MasterData.update({'_id':_id},{"$set":data},upsert=False)
1008
        return {1:'Data updated successfully.'}
1009
    else:
1010
        _id = data.pop('_id')
1011
        skuBundleId = data.pop('skuBundleId')
14612 kshitij.so 1012
        data['updatedOn'] = to_java_date(datetime.now())
14640 kshitij.so 1013
        data['identifier'] = str(data['identifier'])
1014
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
14597 kshitij.so 1015
        get_mongo_connection().Catalog.MasterData.update({'_id':_id},{"$set":data},upsert=False)
1016
        similarItems = get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId})
1017
        for item in similarItems:
14598 kshitij.so 1018
            if item['_id'] == _id:
14597 kshitij.so 1019
                continue
1020
            item['updatedOn'] = to_java_date(datetime.now())
1021
            item['thumbnail'] = data['thumbnail']
1022
            item['category'] = data['category']
1023
            item['category_id'] = data['category_id']
1024
            item['tagline'] = data['tagline']
1025
            item['is_shortage'] = data['is_shortage']
1026
            item['mrp'] = data['mrp']
14611 kshitij.so 1027
            item['status'] = data['status']
14852 kshitij.so 1028
            item['maxPrice'] = data['maxPrice']
14599 kshitij.so 1029
            similar_item_id = item.pop('_id')
1030
            get_mongo_connection().Catalog.MasterData.update({'_id':similar_item_id},{"$set":item},upsert=False)
14597 kshitij.so 1031
        return {1:'Data updated successfully.'}
14619 kshitij.so 1032
 
1033
def getLiveCricScore():
1034
    return mc.get('liveScore')
14852 kshitij.so 1035
 
1036
def addBundleToNotification(data):
1037
    try:
1038
        collection = get_mongo_connection().Catalog.Notification
1039
        cursor = collection.find({'skuBundleId':data['skuBundleId']})
1040
        if cursor.count() > 0:
1041
            return {0:"SkuBundleId information already present."}
1042
        else:
1043
            collection.insert(data)
1044
            return {1:'Data updated successfully.'}
1045
    except:
1046
        return {0:'Unable to add data.'}
1047
 
1048
def getAllNotifications(offset, limit):
1049
    data = []
1050
    collection = get_mongo_connection().Catalog.Notification
1051
    cursor = collection.find().skip(offset).limit(limit)
1052
    for val in cursor:
1053
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
1054
        if len(master) > 0:
1055
            val['brand'] = master[0]['brand']
1056
            val['source_product_name'] = master[0]['source_product_name']
1057
            val['skuBundleId'] = master[0]['skuBundleId']
1058
        else:
1059
            val['brand'] = ""
1060
            val['source_product_name'] = ""
1061
            val['skuBundleId'] = ""
1062
        data.append(val)
1063
    return data
14997 kshitij.so 1064
 
1065
def getBrandsForFilter(category_id):
1066
    if mc.get("brandFilter") is None:
1067
        tabData, mobData = [], []
1068
        mobileDeals = get_mongo_connection().Catalog.Deals.aggregate([
1069
                                                                      {"$match":{"category_id":3,"showDeal":1}
1070
                                                                    },
1071
                                                                 {"$group" : 
1072
                                                                  {'_id':{'brand_id':'$brand_id','brand':'$brand'},'count':{'$sum':1}}
1073
                                                                  }
1074
                                                                ])
14588 kshitij.so 1075
 
14997 kshitij.so 1076
        tabletDeals = get_mongo_connection().Catalog.Deals.aggregate([
1077
                                                                      {"$match":{"category_id":5,"showDeal":1}
1078
                                                                    },
1079
                                                                 {"$group" : 
1080
                                                                  {'_id':{'brand_id':'$brand_id','brand':'$brand'},'count':{'$sum':1}}
1081
                                                                  }
1082
                                                                ])
1083
 
1084
        allDeals = get_mongo_connection().Catalog.Deals.aggregate([
1085
                                                                   {"$match":{"showDeal":1}
1086
                                                                    },
1087
                                                                 {"$group" : 
1088
                                                                  {'_id':{'brand_id':'$brand_id','brand':'$brand'},'count':{'$sum':1}}
1089
                                                                  }
1090
                                                                ])
1091
        #print mobileDeals
1092
        #print "==========Mobile data ends=========="
1093
 
1094
        #print tabletDeals
1095
        #print "==========Tablet data ends=========="
1096
 
1097
        #print allDeals
1098
        #print "==========All deal data ends========="
1099
 
1100
        for mobileDeal in mobileDeals['result']:
1101
            if mobileDeal.get('_id').get('brand_id') != 0:
1102
                tempMap = {}
1103
                tempMap['brand'] = mobileDeal.get('_id').get('brand')
1104
                tempMap['brand_id'] = mobileDeal.get('_id').get('brand_id')
1105
                tempMap['count'] = mobileDeal.get('count')
1106
                mobData.append(tempMap)
1107
 
1108
        for tabletDeal in tabletDeals['result']:
1109
            if tabletDeal.get('_id').get('brand_id') != 0:
1110
                tempMap = {}
1111
                tempMap['brand'] = tabletDeal.get('_id').get('brand')
1112
                tempMap['brand_id'] = tabletDeal.get('_id').get('brand_id')
1113
                tempMap['count'] = tabletDeal.get('count')
1114
                tabData.append(tempMap)
1115
 
1116
 
1117
        brandMap = {}
1118
        for allDeal in allDeals['result']:
1119
            if allDeal.get('_id').get('brand_id') != 0:
1120
                if brandMap.has_key(allDeal.get('_id').get('brand')):
1121
                    brand_ids = brandMap.get(allDeal.get('_id').get('brand'))
1122
                    brand_ids.append(allDeal.get('_id').get('brand_id'))
1123
                    brandMap[allDeal.get('_id').get('brand')] = brand_ids
1124
                else:
1125
                    temp = []
1126
                    temp.append(allDeal.get('_id').get('brand_id'))
1127
                    brandMap[allDeal.get('_id').get('brand')] = temp
1128
 
1129
        mc.set("brandFilter",{0:brandMap, 3:mobData, 5:tabData}, 600)  
1130
 
1131
    return mc.get("brandFilter").get(category_id)                
1132
 
1133
 
1134
 
1135
 
13572 kshitij.so 1136
def main():
14997 kshitij.so 1137
    print (getBrandsForFilter(3))
13811 kshitij.so 1138
 
13921 kshitij.so 1139
 
13572 kshitij.so 1140
if __name__=='__main__':
13932 amit.gupta 1141
    main()