Subversion Repositories SmartDukaan

Rev

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