Subversion Repositories SmartDukaan

Rev

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