Subversion Repositories SmartDukaan

Rev

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

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