Subversion Repositories SmartDukaan

Rev

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

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