Subversion Repositories SmartDukaan

Rev

Rev 14668 | Rev 14671 | 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
 
318
def __populateCache(userId):
319
    print "Populating memcache for userId",userId
320
    outer_query = []
321
    outer_query.append({"showDeal":1})
322
    query = {}
323
    query['$gt'] = 0
324
    outer_query.append({'totalPoints':query})
325
    brandPrefMap = {}
326
    pricePrefMap = {}
327
    actionsMap = {}
328
    brand_p = session.query(price_preferences).filter_by(user_id=userId).all()
329
    for x in brand_p:
330
        pricePrefMap[x.category_id] = [x.min_price,x.max_price]
331
    for x in session.query(brand_preferences).filter_by(user_id=userId).all():
332
        temp_map = {}
333
        if brandPrefMap.has_key((x.brand).strip().upper()):
334
            val = brandPrefMap.get((x.brand).strip().upper())
335
            temp_map[x.category_id] = 1 if x.status == 'show' else 0
336
            val.append(temp_map)
337
        else:
338
            temp = []
339
            temp_map[x.category_id] = 1 if x.status == 'show' else 0
340
            temp.append(temp_map)
341
            brandPrefMap[(x.brand).strip().upper()] = temp
342
 
343
    for x in session.query(user_actions).filter_by(user_id=userId).all():
344
        actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0
14323 kshitij.so 345
    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 346
    all_category_deals = []
347
    mobile_deals = []
348
    tablet_deals = []
349
    for deal in all_deals:
350
        if actionsMap.get(deal['_id']) == 0:
351
            fav_weight =.25
352
        elif actionsMap.get(deal['_id']) == 1:
353
            fav_weight = 1.5
354
        else:
355
            fav_weight = 1
356
 
357
        if brandPrefMap.get(deal['brand'].strip().upper()) is not None:
358
            brand_weight = 1
359
            for brandInfo in brandPrefMap.get(deal['brand'].strip().upper()):
360
                if brandInfo.get(deal['category_id']) is not None:
361
                    if brandInfo.get(deal['category_id']) == 1:
14055 kshitij.so 362
                        brand_weight = 2.0
14037 kshitij.so 363
        else:
364
            brand_weight = 1
365
 
366
        if pricePrefMap.get(deal['category_id']) is not None:
367
 
368
            if deal['available_price'] >= pricePrefMap.get(deal['category_id'])[0] and deal['available_price'] <= pricePrefMap.get(deal['category_id'])[1]:
369
                asp_weight = 1.5
370
            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]:
371
                asp_weight = 1.2
372
            else:
373
                asp_weight = 1
374
        else:
375
            asp_weight = 1
376
 
377
        persPoints = deal['totalPoints'] * fav_weight * brand_weight * asp_weight
378
        deal['persPoints'] = persPoints
379
 
380
        if deal['category_id'] ==3:
381
            mobile_deals.append(deal)
382
        elif deal['category_id'] ==5:
383
            tablet_deals.append(deal)
384
        else:
385
            continue
386
        all_category_deals.append(deal)
387
 
14144 kshitij.so 388
    session.close()
14037 kshitij.so 389
    mem_cache_val = {3:mobile_deals, 5:tablet_deals, 0:all_deals}
390
    mc.set(str(userId), mem_cache_val)
391
 
392
 
14531 kshitij.so 393
def __populateFeaturedDeals():
394
    all_category_fd = []
395
    mobile_fd = []
396
    tablet_fd = []
14550 kshitij.so 397
    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 398
    for activeFeaturedDeal in activeFeaturedDeals:
399
        for k,v in activeFeaturedDeal['rankDetails']:
400
            featuredDeal = FeaturedDeals(activeFeaturedDeal['sku'], int(k), activeFeaturedDeal['thresholdPrice'], int(v))
401
            if featuredDeal.category_id == 0:
402
                all_category_fd.append(featuredDeal)
403
            elif featuredDeal.category_id == 3:
404
                mobile_fd.append(featuredDeal)
405
            elif featuredDeal.category_id == 5:
406
                tablet_fd.append(featuredDeal)
407
            else:
408
                continue
14550 kshitij.so 409
    mc.set("featured_deals_category_"+str(0), all_category_fd, 3600)
410
    mc.set("featured_deals_category_"+str(3), mobile_fd, 3600)
411
    mc.set("featured_deals_category_"+str(5), tablet_fd, 3600)
14037 kshitij.so 412
 
413
def getNewDeals(userId, category_id, offset, limit, sort, direction):
13922 kshitij.so 414
    if not bool(cashBackMap):
13921 kshitij.so 415
        populateCashBack()
14037 kshitij.so 416
 
14550 kshitij.so 417
    try:
418
        if mc.get("featured_deals_category_"+str(category_id)) is None:
419
            __populateFeaturedDeals()
420
    except:
421
        pass 
14531 kshitij.so 422
 
13771 kshitij.so 423
    rank = 1
14037 kshitij.so 424
    dealsMap = {}
425
    user_specific_deals = mc.get(str(userId))
426
    if user_specific_deals is None:
427
        __populateCache(userId)
428
        user_specific_deals = mc.get(str(userId))
14038 kshitij.so 429
    else:
430
        print "Getting user deals from cache"
14037 kshitij.so 431
    category_specific_deals = user_specific_deals.get(category_id)
432
 
433
    if sort is None or direction is None:
434
        sorted_deals = sorted(category_specific_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
435
    else:
436
        if sort == "bestSellerPoints":
437
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['bestSellerPoints'], x['rank'], x['nlcPoints']),reverse=True)
438
        else:
439
            if direction == -1:
440
                rev = True
441
            else:
442
                rev = False
443
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['available_price']),reverse=rev)
444
 
445
    for d in sorted_deals[offset:offset+limit]:
446
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
447
        if not dealsMap.has_key(item[0]['identifier']):
448
            item[0]['dealRank'] = rank
449
            item[0]['persPoints'] = d['persPoints']
14322 kshitij.so 450
            if d['dealType'] == 1 and d['source_id'] ==1:
451
                item[0]['marketPlaceUrl'] = "http://www.amazon.in/dp/%s"%(item[0]['identifier'].strip()) 
14037 kshitij.so 452
            try:
453
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
454
                if not cashBack or cashBack.get('cash_back_status')!=1:
455
                    item[0]['cash_back_type'] = 0
456
                    item[0]['cash_back'] = 0
457
                else:
458
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
459
                    item[0]['cash_back'] = cashBack['cash_back']
460
            except:
461
                print "Error in adding cashback to deals"
462
                item[0]['cash_back_type'] = 0
463
                item[0]['cash_back'] = 0
464
            dealsMap[item[0]['identifier']] = item[0]
465
 
466
            rank +=1
467
    return sorted(dealsMap.values(), key=itemgetter('dealRank'))
468
 
469
 
470
def getDeals(userId, category_id, offset, limit, sort, direction):
471
    if not bool(cashBackMap):
472
        populateCashBack()
473
    rank = 1
13771 kshitij.so 474
    deals = {}
13910 kshitij.so 475
    outer_query = []
476
    outer_query.append({"showDeal":1})
477
    query = {}
478
    query['$gt'] = 0
479
    outer_query.append({'totalPoints':query})
480
    if category_id in (3,5):
481
        outer_query.append({'category_id':category_id})
13803 kshitij.so 482
    if sort is None or direction is None:
483
        direct = -1
13910 kshitij.so 484
        print outer_query
485
        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 486
    else:
13910 kshitij.so 487
        print outer_query
13803 kshitij.so 488
        direct = direction
13910 kshitij.so 489
        if sort == "bestSellerPoints":
490
            print "yes,sorting by bestSellerPoints"
491
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
492
        else:
493
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 494
    for d in data:
495
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
496
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 497
            item[0]['dealRank'] = rank
498
            try:
499
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
500
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 501
                    item[0]['cash_back_type'] = 0
502
                    item[0]['cash_back'] = 0
13921 kshitij.so 503
                else:
13928 kshitij.so 504
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
505
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 506
            except:
507
                print "Error in adding cashback to deals"
13928 kshitij.so 508
                item[0]['cash_back_type'] = 0
509
                item[0]['cash_back'] = 0
13771 kshitij.so 510
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 511
 
13771 kshitij.so 512
            rank +=1
13785 kshitij.so 513
    return sorted(deals.values(), key=itemgetter('dealRank'))
514
 
515
def getItem(skuId):
14113 kshitij.so 516
    if not bool(cashBackMap):
517
        populateCashBack()
13795 kshitij.so 518
    try:
519
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
14107 kshitij.so 520
        for sku in skuData:
521
            try:
522
                cashBack = __getCashBack(sku['_id'], sku['source_id'], sku['category_id'])
523
                if not cashBack or cashBack.get('cash_back_status')!=1:
524
                    sku['cash_back_type'] = 0
525
                    sku['cash_back'] = 0
526
                else:
527
                    sku['cash_back_type'] = cashBack['cash_back_type']
528
                    sku['cash_back'] = cashBack['cash_back']
529
            except:
530
                print "Error in adding cashback to deals"
531
                sku['cash_back_type'] = 0
532
                sku['cash_back'] = 0
14629 kshitij.so 533
            sku['in_stock'] = int(sku['in_stock'])
534
            sku['is_shortage'] = int(sku['is_shortage'])
535
            sku['category_id'] = int(sku['category_id'])
536
            sku['status'] = int(sku['status'])
13785 kshitij.so 537
        return skuData
13795 kshitij.so 538
    except:
539
        return [{}]
13836 kshitij.so 540
 
13921 kshitij.so 541
def __getCashBack(skuId, source_id, category_id):
542
    itemCashBack = itemCashBackMap.get(skuId)
543
    if itemCashBack is not None:
544
        return itemCashBack
545
 
546
    sourceCashBack = cashBackMap.get(source_id)
547
    if sourceCashBack is not None and len(sourceCashBack) > 0:
548
        for cashBack in sourceCashBack:
549
            if cashBack.get(category_id) is None:
550
                continue
551
            else:
552
                return cashBack.get(category_id)
553
    else:
554
        return {}
555
 
13836 kshitij.so 556
def getCashBackDetails(identifier, source_id):
13922 kshitij.so 557
    if not bool(cashBackMap):
13921 kshitij.so 558
        populateCashBack()
559
 
13836 kshitij.so 560
    """Need to add item level cashback, no data available right now."""
13771 kshitij.so 561
 
13921 kshitij.so 562
    if source_id in (1,2,4,5):
13839 kshitij.so 563
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 564
    elif source_id == 3:
13839 kshitij.so 565
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 566
    else:
567
        return {}
13836 kshitij.so 568
    if len(skuData) > 0:
13921 kshitij.so 569
 
570
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
571
        if itemCashBack is not None:
572
            return itemCashBack
573
 
574
        sourceCashBack = cashBackMap.get(source_id)
575
        if sourceCashBack is not None and len(sourceCashBack) > 0:
576
            for cashBack in sourceCashBack:
577
                if cashBack.get(skuData[0]['category_id']) is None:
578
                    continue
579
                else:
580
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 581
        else:
582
            return {} 
583
    else:
584
        return {}
13986 amit.gupta 585
 
14398 amit.gupta 586
def getImgSrc(identifier, source_id):
587
    skuData = None
588
    if source_id in (1,2,4,5):
14414 amit.gupta 589
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'identifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 590
    elif source_id == 3:
14414 amit.gupta 591
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'secondaryIdentifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 592
    if skuData is None:
593
        return {}
594
    else:
595
        return {'thumbnail':skuData.get('thumbnail')}
13986 amit.gupta 596
 
597
def next_weekday(d, weekday):
598
    days_ahead = weekday - d.weekday()
599
    if days_ahead <= 0: # Target day already happened this week
600
        days_ahead += 7
601
    return d + timedelta(days_ahead)
602
 
13771 kshitij.so 603
 
13970 kshitij.so 604
def getAllDealerPrices(offset, limit):
605
    data = []
606
    collection = get_mongo_connection().Catalog.SkuDealerPrices
607
    cursor = collection.find().skip(offset).limit(limit)
608
    for val in cursor:
609
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
610
        if len(master) > 0:
14069 kshitij.so 611
            val['brand'] = master[0]['brand']
612
            val['source_product_name'] = master[0]['source_product_name']
613
            val['skuBundleId'] = master[0]['skuBundleId']
13970 kshitij.so 614
        else:
615
            val['brand'] = ""
616
            val['source_product_name'] = ""
617
            val['skuBundleId'] = ""
618
        data.append(val)
619
    return data
620
 
14553 kshitij.so 621
def addSkuDealerPrice(data, multi):
622
    if multi != 1:
623
        collection = get_mongo_connection().Catalog.SkuDealerPrices
624
        cursor = collection.find({"sku":data['sku']})
625
        if cursor.count() > 0:
626
            return {0:"Sku information already present."}
627
        else:
628
            collection.insert(data)
629
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
630
            return {1:"Data added successfully"}
13970 kshitij.so 631
    else:
14553 kshitij.so 632
        skuIds = __getBundledSkusfromSku(data['sku'])
633
        for sku in skuIds:
634
            data['sku'] = sku.get('_id')
635
            collection = get_mongo_connection().Catalog.SkuDealerPrices
636
            cursor = collection.find({"sku":data['sku']})
637
            if cursor.count() > 0:
638
                continue
639
            else:   
14558 kshitij.so 640
                data.pop('_id',None)
14553 kshitij.so 641
                collection.insert(data)
642
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13970 kshitij.so 643
        return {1:"Data added successfully"}
14553 kshitij.so 644
 
645
 
13970 kshitij.so 646
 
647
def updateSkuDealerPrice(data, _id):
648
    try:
649
        collection = get_mongo_connection().Catalog.SkuDealerPrices
650
        collection.update({'_id':ObjectId(_id)},{"$set":{'dp':data['dp']}},upsert=False, multi = False)
651
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
652
        return {1:"Data updated successfully"}
653
    except:
654
        return {0:"Data not updated."}
655
 
656
def updateExceptionalNlc(data, _id):
657
    try:
658
        collection = get_mongo_connection().Catalog.ExceptionalNlc
659
        collection.update({'_id':ObjectId(_id)},{"$set":{'maxNlc':data['maxNlc'], 'minNlc':data['minNlc'], 'overrideNlc':data['overrideNlc']}},upsert=False, multi = False)
660
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
661
        return {1:"Data updated successfully"}
662
    except:
663
        return {0:"Data not updated."}
664
 
14041 kshitij.so 665
def resetCache(userId):
14043 kshitij.so 666
    try:
667
        mc.delete(userId)
668
        return {1:'Cache cleared.'}
669
    except:
670
        return {0:'Unable to clear cache.'}
671
 
14575 kshitij.so 672
def updateCollection(data, multi):
14083 kshitij.so 673
    print data
14575 kshitij.so 674
    if multi!=1:
675
        try:
676
            collection = get_mongo_connection().Catalog[data['class']]
677
            class_name = data.pop('class')
678
            if class_name == "SkuSchemeDetails":
679
                data['addedOn'] = to_java_date(datetime.now())
680
            _id = data.pop('oid')
681
            result = collection.update({'_id':ObjectId(_id)},{"$set":data},upsert=False, multi = False)
682
            record = list(collection.find({'_id':ObjectId(_id)}))
683
            if class_name !="CategoryDiscount":
684
                get_mongo_connection().Catalog.MasterData.update({'_id':record[0]['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}})
685
            else:
686
                get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
687
                                                                 {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
688
            return {1:"Data updated successfully"}
689
        except Exception as e:
690
            print e
691
            return {0:"Data not updated."}
692
    else:
693
        try:
694
            collection = get_mongo_connection().Catalog[data['class']]
695
            class_name = data.pop('class')
696
            _id = data.pop('oid')
697
            record = list(collection.find({'_id':ObjectId(_id)}))
698
            skuIds = __getBundledSkusfromSku(record[0]['sku'])
699
            for sku in skuIds:
700
                if class_name == "SkuSchemeDetails":
701
                    data['addedOn'] = to_java_date(datetime.now())
14582 kshitij.so 702
                data['sku'] = sku.get('_id')
14575 kshitij.so 703
                data.pop('_id',None)
14583 kshitij.so 704
                collection.update({'sku':sku.get('_id')},{"$set":data},upsert=False,multi=False)
14575 kshitij.so 705
            get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14580 kshitij.so 706
            return {1:"Data updatedsuccessfully"}
14575 kshitij.so 707
        except Exception as e:
708
            print e
709
            return {0:"Data not updated."}
710
 
14076 kshitij.so 711
 
14553 kshitij.so 712
def addNegativeDeals(data, multi):
713
    if multi !=1: 
714
        collection = get_mongo_connection().Catalog.NegativeDeals
715
        cursor = collection.find({"sku":data['sku']})
716
        if cursor.count() > 0:
717
            return {0:"Sku information already present."}
718
        else:
719
            collection.insert(data)
720
            return {1:"Data added successfully"}
14481 kshitij.so 721
    else:
14553 kshitij.so 722
        skuIds = __getBundledSkusfromSku(data['sku'])
723
        for sku in skuIds:
724
            data['sku'] = sku.get('_id')
725
            collection = get_mongo_connection().Catalog.NegativeDeals
726
            cursor = collection.find({"sku":data['sku']})
727
            if cursor.count() > 0:
728
                continue
729
            else:
14558 kshitij.so 730
                data.pop('_id',None)
14553 kshitij.so 731
                collection.insert(data)
14481 kshitij.so 732
        return {1:"Data added successfully"}
733
 
734
def getAllNegativeDeals(offset, limit):
735
    data = []
736
    collection = get_mongo_connection().Catalog.NegativeDeals
737
    cursor = collection.find().skip(offset).limit(limit)
738
    for val in cursor:
739
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
740
        if len(master) > 0:
741
            val['brand'] = master[0]['brand']
742
            val['source_product_name'] = master[0]['source_product_name']
743
            val['skuBundleId'] = master[0]['skuBundleId']
744
        else:
745
            val['brand'] = ""
746
            val['source_product_name'] = ""
747
            val['skuBundleId'] = ""
748
        data.append(val)
749
    return data
750
 
751
def getAllManualDeals(offset, limit):
752
    data = []
753
    collection = get_mongo_connection().Catalog.ManualDeals
14495 kshitij.so 754
    cursor = collection.find({'endDate':{'$gte':to_java_date(datetime.now())}}).skip(offset).limit(limit)
14481 kshitij.so 755
    for val in cursor:
756
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
757
        if len(master) > 0:
758
            val['brand'] = master[0]['brand']
759
            val['source_product_name'] = master[0]['source_product_name']
760
            val['skuBundleId'] = master[0]['skuBundleId']
761
        else:
762
            val['brand'] = ""
763
            val['source_product_name'] = ""
764
            val['skuBundleId'] = ""
765
        data.append(val)
766
    return data
14076 kshitij.so 767
 
14553 kshitij.so 768
def addManualDeal(data, multi):
769
    if multi !=1:
770
        collection = get_mongo_connection().Catalog.ManualDeals
771
        cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
772
        if cursor.count() > 0:
773
            return {0:"Sku information already present."}
774
        else:
775
            collection.insert(data)
776
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
777
            return {1:"Data added successfully"}
14481 kshitij.so 778
    else:
14553 kshitij.so 779
        skuIds = __getBundledSkusfromSku(data['sku'])
780
        for sku in skuIds:
781
            data['sku'] = sku.get('_id')
782
            collection = get_mongo_connection().Catalog.ManualDeals
783
            cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
784
            if cursor.count() > 0:
785
                continue
786
            else:
14558 kshitij.so 787
                data.pop('_id',None)
14553 kshitij.so 788
                collection.insert(data)
789
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14481 kshitij.so 790
        return {1:"Data added successfully"}
14553 kshitij.so 791
 
14481 kshitij.so 792
def deleteDocument(data):
793
    print data
794
    try:
795
        collection = get_mongo_connection().Catalog[data['class']]
796
        class_name = data.pop('class')
797
        _id = data.pop('oid')
798
        record = list(collection.find({'_id':ObjectId(_id)}))
799
        collection.remove({'_id':ObjectId(_id)})
800
        if class_name !="CategoryDiscount":
801
            get_mongo_connection().Catalog.MasterData.update({'_id':record[0]['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}})
802
        else:
803
            get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
804
                                                             {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
805
        return {1:"Document deleted successfully"}
806
    except Exception as e:
807
        print e
808
        return {0:"Document not deleted."}
13970 kshitij.so 809
 
14482 kshitij.so 810
def searchMaster(offset, limit, search_term):
811
    data = []
14531 kshitij.so 812
    if search_term is not None:
14551 kshitij.so 813
        terms = search_term.split(' ')
814
        outer_query = []
815
        for term in terms:
816
            outer_query.append({"source_product_name":re.compile(term, re.IGNORECASE)})
14531 kshitij.so 817
        try:
14551 kshitij.so 818
            collection = get_mongo_connection().Catalog.MasterData.find({"$and":outer_query,'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
14531 kshitij.so 819
            for record in collection:
820
                data.append(record)
821
        except:
822
            pass
823
    else:
824
        collection = get_mongo_connection().Catalog.MasterData.find({'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
14482 kshitij.so 825
        for record in collection:
826
            data.append(record)
827
    return data
14481 kshitij.so 828
 
14495 kshitij.so 829
def getAllFeaturedDeals(offset, limit):
830
    data = []
831
    collection = get_mongo_connection().Catalog.FeaturedDeals
832
    cursor = collection.find({'endDate':{'$gte':to_java_date(datetime.now())}}).skip(offset).limit(limit)
833
    for val in cursor:
834
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
835
        if len(master) > 0:
836
            val['brand'] = master[0]['brand']
837
            val['source_product_name'] = master[0]['source_product_name']
838
            val['skuBundleId'] = master[0]['skuBundleId']
839
        else:
840
            val['brand'] = ""
841
            val['source_product_name'] = ""
842
            val['skuBundleId'] = ""
843
        data.append(val)
844
    return data
845
 
14553 kshitij.so 846
def addFeaturedDeal(data, multi):
847
    if multi !=1:
848
        collection = get_mongo_connection().Catalog.FeaturedDeals
849
        cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
850
        if cursor.count() > 0:
851
            return {0:"Sku information already present."}
852
        else:
853
            collection.insert(data)
854
            get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
855
            return {1:"Data added successfully"}
14495 kshitij.so 856
    else:
14553 kshitij.so 857
        skuIds = __getBundledSkusfromSku(data['sku'])
858
        for sku in skuIds:
859
            data['sku'] = sku.get('_id')
860
            collection = get_mongo_connection().Catalog.FeaturedDeals
861
            cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
862
            if cursor.count() > 0:
863
                continue
864
            else:
14558 kshitij.so 865
                data.pop('_id',None)
14553 kshitij.so 866
                collection.insert(data)
867
        get_mongo_connection().Catalog.MasterData.update({'skuBundleId':sku.get('skuBundleId')},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
14495 kshitij.so 868
        return {1:"Data added successfully"}
869
 
14499 kshitij.so 870
def searchCollection(class_name, sku, skuBundleId):
14497 kshitij.so 871
    data = []
872
    collection = get_mongo_connection().Catalog[class_name]
14499 kshitij.so 873
    if sku is not None:
874
        cursor = collection.find({'sku':sku})
875
        for val in cursor:
876
            master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
877
            if len(master) > 0:
878
                val['brand'] = master[0]['brand']
879
                val['source_product_name'] = master[0]['source_product_name']
880
                val['skuBundleId'] = master[0]['skuBundleId']
881
            else:
882
                val['brand'] = ""
883
                val['source_product_name'] = ""
884
                val['skuBundleId'] = ""
885
            data.append(val)
886
        return data
887
    else:
14562 kshitij.so 888
        skuIds = get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId}).distinct('_id')
14499 kshitij.so 889
        for sku in skuIds:
890
            cursor = collection.find({'sku':sku})
891
            for val in cursor:
892
                master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
893
                if len(master) > 0:
894
                    val['brand'] = master[0]['brand']
895
                    val['source_product_name'] = master[0]['source_product_name']
896
                    val['skuBundleId'] = master[0]['skuBundleId']
897
                else:
898
                    val['brand'] = ""
899
                    val['source_product_name'] = ""
900
                    val['skuBundleId'] = ""
901
                data.append(val)
902
        return data
14495 kshitij.so 903
 
14588 kshitij.so 904
def addNewItem(data):
14594 kshitij.so 905
    try:
906
        data['updatedOn'] = to_java_date(datetime.now())
907
        data['addedOn'] = to_java_date(datetime.now())
908
        data['priceUpdatedOn'] = to_java_date(datetime.now())
909
        max_id = list(get_mongo_connection().Catalog.MasterData.find().sort([('_id',pymongo.DESCENDING)]).limit(1))
910
        max_bundle = list(get_mongo_connection().Catalog.MasterData.find().sort([('skuBundleId',pymongo.DESCENDING)]).limit(1))
911
        data['_id'] = max_id[0]['_id'] + 1
912
        data['skuBundleId'] = max_bundle[0]['skuBundleId'] + 1
913
        data['identifier'] = str(data['identifier'])
914
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
915
        get_mongo_connection().Catalog.MasterData.insert(data)
916
        return {1:'Data added successfully'}
917
    except Exception as e:
918
        print e
919
        return {0:'Unable to add data.'}
14588 kshitij.so 920
 
921
def addItemToExistingBundle(data):
922
    try:
923
        data['updatedOn'] = to_java_date(datetime.now())
924
        data['addedOn'] = to_java_date(datetime.now())
925
        data['priceUpdatedOn'] = to_java_date(datetime.now())
14593 kshitij.so 926
        max_id = list(get_mongo_connection().Catalog.MasterData.find().sort([('_id',pymongo.DESCENDING)]).limit(1))
14590 kshitij.so 927
        data['_id'] = max_id[0]['_id'] + 1
14594 kshitij.so 928
        data['identifier'] = str(data['identifier'])
929
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
14588 kshitij.so 930
        get_mongo_connection().Catalog.MasterData.insert(data)
931
        return {1:'Data added successfully.'}
14594 kshitij.so 932
    except Exception as e:
933
        print e
14588 kshitij.so 934
        return {0:'Unable to add data.'}
935
 
936
def updateMaster(data, multi):
14640 kshitij.so 937
    print data
14597 kshitij.so 938
    if multi != 1:
939
        _id = data.pop('_id')
940
        skuBundleId = data.pop('skuBundleId')
941
        data['updatedOn'] = to_java_date(datetime.now())
14640 kshitij.so 942
        data['identifier'] = str(data['identifier'])
943
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
14597 kshitij.so 944
        get_mongo_connection().Catalog.MasterData.update({'_id':_id},{"$set":data},upsert=False)
945
        return {1:'Data updated successfully.'}
946
    else:
947
        _id = data.pop('_id')
948
        skuBundleId = data.pop('skuBundleId')
14612 kshitij.so 949
        data['updatedOn'] = to_java_date(datetime.now())
14640 kshitij.so 950
        data['identifier'] = str(data['identifier'])
951
        data['secondaryIdentifier'] = str(data['secondaryIdentifier'])
14597 kshitij.so 952
        get_mongo_connection().Catalog.MasterData.update({'_id':_id},{"$set":data},upsert=False)
953
        similarItems = get_mongo_connection().Catalog.MasterData.find({'skuBundleId':skuBundleId})
954
        for item in similarItems:
14598 kshitij.so 955
            if item['_id'] == _id:
14597 kshitij.so 956
                continue
957
            item['updatedOn'] = to_java_date(datetime.now())
958
            item['thumbnail'] = data['thumbnail']
959
            item['category'] = data['category']
960
            item['category_id'] = data['category_id']
961
            item['tagline'] = data['tagline']
962
            item['is_shortage'] = data['is_shortage']
963
            item['mrp'] = data['mrp']
14611 kshitij.so 964
            item['status'] = data['status']
14599 kshitij.so 965
            similar_item_id = item.pop('_id')
966
            get_mongo_connection().Catalog.MasterData.update({'_id':similar_item_id},{"$set":item},upsert=False)
14597 kshitij.so 967
        return {1:'Data updated successfully.'}
14619 kshitij.so 968
 
969
def getLiveCricScore():
970
    return mc.get('liveScore')
14588 kshitij.so 971
 
13572 kshitij.so 972
def main():
14553 kshitij.so 973
    print __getBundledSkusfromSku(1)
13811 kshitij.so 974
 
13921 kshitij.so 975
 
13572 kshitij.so 976
if __name__=='__main__':
13932 amit.gupta 977
    main()