Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
13928 kshitij.so 1
import pymongo
14037 kshitij.so 2
from elixir import *
13572 kshitij.so 3
from datetime import datetime
13986 amit.gupta 4
from datetime import timedelta
13927 amit.gupta 5
from dtr.main import Store
13785 kshitij.so 6
from dtr.utils.utils import to_java_date
13970 kshitij.so 7
from operator import itemgetter
8
from bson.objectid import ObjectId
14037 kshitij.so 9
from dtr.storage import DataService
10
from dtr.storage.DataService import price_preferences, brand_preferences, \
11
user_actions
12
from dtr.storage.MemCache import MemCache
13572 kshitij.so 13
 
14
con = None
13907 kshitij.so 15
cashBackMap = {}
13921 kshitij.so 16
itemCashBackMap = {}
13572 kshitij.so 17
 
14037 kshitij.so 18
DataService.initialize(db_hostname="localhost")
19
mc = MemCache("127.0.0.1")
20
 
13572 kshitij.so 21
def get_mongo_connection(host='localhost', port=27017):
22
    global con
23
    if con is None:
24
        print "Establishing connection %s host and port %d" %(host,port)
25
        try:
26
            con = pymongo.MongoClient(host, port)
27
        except Exception, e:
28
            print e
29
            return None
30
    return con
31
 
13907 kshitij.so 32
def populateCashBack():
13921 kshitij.so 33
    print "Populating cashback"
13907 kshitij.so 34
    global cashBackMap
13921 kshitij.so 35
    global itemCashBackMap
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
13907 kshitij.so 57
 
13572 kshitij.so 58
def addCategoryDiscount(data):
13970 kshitij.so 59
    collection = get_mongo_connection().Catalog.CategoryDiscount
13572 kshitij.so 60
    query = []
61
    data['brand'] = data['brand'].strip().upper()
13970 kshitij.so 62
    data['discountType'] = data['discountType'].upper().strip()
13572 kshitij.so 63
    query.append({"brand":data['brand']})
64
    query.append({"category_id":data['category_id']})
65
    r = collection.find({"$and":query})
66
    if r.count() > 0:
13639 kshitij.so 67
        return {0:"Brand & Category info already present."}
13572 kshitij.so 68
    else:
69
        collection.insert(data)
13970 kshitij.so 70
        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 71
        return {1:"Data added successfully"}
13572 kshitij.so 72
 
13970 kshitij.so 73
def updateCategoryDiscount(data,_id):
74
    try:
75
        collection = get_mongo_connection().Catalog.CategoryDiscount
76
        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)
77
        get_mongo_connection().Catalog.MasterData.update({'brand':data['brand'],'category_id':data['category_id']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
78
        return {1:"Data updated successfully"}
79
    except:
80
        return {0:"Data not updated."}
81
 
82
 
13572 kshitij.so 83
def getAllCategoryDiscount():
84
    data = []
13970 kshitij.so 85
    collection = get_mongo_connection().Catalog.CategoryDiscount
13572 kshitij.so 86
    cursor = collection.find()
87
    for val in cursor:
88
        data.append(val)
89
    return data
90
 
91
def addSchemeDetailsForSku(data):
13970 kshitij.so 92
    collection = get_mongo_connection().Catalog.SkuSchemeDetails
13572 kshitij.so 93
    data['addedOn'] = to_java_date(datetime.now())
94
    collection.insert(data)
13639 kshitij.so 95
    return {1:"Data added successfully"}
13572 kshitij.so 96
 
14069 kshitij.so 97
def getAllSkuWiseSchemeDetails(offset, limit):
13572 kshitij.so 98
    data = []
13970 kshitij.so 99
    collection = get_mongo_connection().Catalog.SkuSchemeDetails
14071 kshitij.so 100
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 101
    for val in cursor:
14069 kshitij.so 102
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
103
        if len(master) > 0:
104
            val['brand'] = master[0]['brand']
105
            val['source_product_name'] = master[0]['source_product_name']
106
            val['skuBundleId'] = master[0]['skuBundleId']
107
        else:
108
            val['brand'] = ""
109
            val['source_product_name'] = ""
110
            val['skuBundleId'] = ""
13572 kshitij.so 111
        data.append(val)
112
    return data
113
 
114
def addSkuDiscountInfo(data):
13970 kshitij.so 115
    collection = get_mongo_connection().Catalog.SkuDiscountInfo
13572 kshitij.so 116
    cursor = collection.find({"sku":data['sku']})
13642 kshitij.so 117
    if cursor.count() > 0:
13639 kshitij.so 118
        return {0:"Sku information already present."}
13572 kshitij.so 119
    else:
120
        collection.insert(data)
13970 kshitij.so 121
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
13639 kshitij.so 122
        return {1:"Data added successfully"}
13572 kshitij.so 123
 
13970 kshitij.so 124
def getallSkuDiscountInfo(offset, limit):
13572 kshitij.so 125
    data = []
13970 kshitij.so 126
    collection = get_mongo_connection().Catalog.SkuDiscountInfo
127
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 128
    for val in cursor:
13970 kshitij.so 129
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
130
        if len(master) > 0:
14069 kshitij.so 131
            val['brand'] = master[0]['brand']
132
            val['source_product_name'] = master[0]['source_product_name']
133
            val['skuBundleId'] = master[0]['skuBundleId']
13970 kshitij.so 134
        else:
135
            val['brand'] = ""
136
            val['source_product_name'] = ""
137
            val['skuBundleId'] = ""
13572 kshitij.so 138
        data.append(val)
139
    return data
140
 
13970 kshitij.so 141
def updateSkuDiscount(data,_id):
142
    try:
143
        collection = get_mongo_connection().Catalog.SkuDiscountInfo
144
        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)
145
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
146
        return {1:"Data updated successfully"}
147
    except:
148
        return {0:"Data not updated."}
149
 
150
 
13572 kshitij.so 151
def addExceptionalNlc(data):
13970 kshitij.so 152
    collection = get_mongo_connection().Catalog.ExceptionalNlc
13572 kshitij.so 153
    cursor = collection.find({"sku":data['sku']})
13642 kshitij.so 154
    if cursor.count() > 0:
13639 kshitij.so 155
        return {0:"Sku information already present."}
13572 kshitij.so 156
    else:
157
        collection.insert(data)
13970 kshitij.so 158
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
13639 kshitij.so 159
        return {1:"Data added successfully"}
13572 kshitij.so 160
 
13970 kshitij.so 161
def getAllExceptionlNlcItems(offset, limit):
13572 kshitij.so 162
    data = []
13970 kshitij.so 163
    collection = get_mongo_connection().Catalog.ExceptionalNlc
14071 kshitij.so 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
 
14005 amit.gupta 178
def getMerchantOrdersByUser(userId, page=1, window=50, searchMap={}):
179
    if searchMap is None:
180
        searchMap = {}
13603 amit.gupta 181
    if page==None:
182
        page = 1
183
 
184
    if window==None:
185
        window = 50
186
    result = {}
13582 amit.gupta 187
    skip = (page-1)*window
14005 amit.gupta 188
 
189
    searchMap['userId'] = userId
13603 amit.gupta 190
    collection = get_mongo_connection().Dtr.merchantOrder
14005 amit.gupta 191
    cursor = collection.find(searchMap).sort("_id",-1)
13603 amit.gupta 192
    total_count = cursor.count()
193
    pages = total_count/window + (0 if total_count%window==0 else 1)  
194
    print "total_count", total_count
195
    if total_count > skip:
13999 amit.gupta 196
        cursor = cursor.skip(skip).limit(window)
13603 amit.gupta 197
        orders = []
198
        for order in cursor:
14002 amit.gupta 199
            del(order["_id"])
200
            orders.append(order)
13603 amit.gupta 201
        result['data'] = orders
202
        result['window'] = window
203
        result['totalCount'] = total_count 
204
        result['currCount'] = cursor.count()
205
        result['totalPages'] = pages
206
        result['currPage'] = page    
207
        return result
208
    else:
209
        return result
13630 kshitij.so 210
 
13927 amit.gupta 211
def getRefunds(userId, page=1, window=10):
212
    if page==None:
213
        page = 1
214
 
215
    if window==None:
13995 amit.gupta 216
        window = 10
13927 amit.gupta 217
    result = {}
218
    skip = (page-1)*window
219
    collection = get_mongo_connection().Dtr.refund
220
    cursor = collection.find({"userId":userId})
221
    total_count = cursor.count()
222
    pages = total_count/window + (0 if total_count%window==0 else 1)  
223
    print "total_count", total_count
224
    if total_count > skip:
13991 amit.gupta 225
        cursor = cursor.skip(skip).limit(window).sort([('batchId',-1)])
13927 amit.gupta 226
        refunds = []
227
        for refund in cursor:
228
            del(refund["_id"])
229
            refunds.append(refund)
230
        result['data'] = refunds
231
        result['window'] = window
232
        result['totalCount'] = total_count 
233
        result['currCount'] = cursor.count()
234
        result['totalPages'] = pages
235
        result['currPage'] = page    
236
        return result
237
    else:
238
        return result
239
 
240
def getPendingRefunds(userId):
13991 amit.gupta 241
    print type(userId)
13927 amit.gupta 242
    result = get_mongo_connection().Dtr.merchantOrder\
243
        .aggregate([
244
                    {'$match':{'subOrders.cashBackStatus':Store.CB_APPROVED, 'userId':userId}},
245
                    {'$unwind':"$subOrders"},
246
                    { 
247
                     '$group':{
248
                               '_id':None,
249
                               'amount': { '$sum':'$subOrders.cashBackAmount'},
250
                               }
251
                     }
13987 amit.gupta 252
                ])['result']
253
 
254
    if len(result)>0:
255
        result = result[0]        
256
        result.pop("_id")
257
    else:
258
        result={}
259
        result['amount'] = 0.0
13988 amit.gupta 260
    result['nextCredit'] = datetime.strftime(next_weekday(datetime.now(), 0),"%Y-%m-%d %H:%M:%S")
13927 amit.gupta 261
    return result
14037 kshitij.so 262
 
263
def __populateCache(userId):
264
    print "Populating memcache for userId",userId
265
    outer_query = []
266
    outer_query.append({"showDeal":1})
267
    query = {}
268
    query['$gt'] = 0
269
    outer_query.append({'totalPoints':query})
270
    brandPrefMap = {}
271
    pricePrefMap = {}
272
    actionsMap = {}
273
    brand_p = session.query(price_preferences).filter_by(user_id=userId).all()
274
    for x in brand_p:
275
        pricePrefMap[x.category_id] = [x.min_price,x.max_price]
276
    for x in session.query(brand_preferences).filter_by(user_id=userId).all():
277
        temp_map = {}
278
        if brandPrefMap.has_key((x.brand).strip().upper()):
279
            val = brandPrefMap.get((x.brand).strip().upper())
280
            temp_map[x.category_id] = 1 if x.status == 'show' else 0
281
            val.append(temp_map)
282
        else:
283
            temp = []
284
            temp_map[x.category_id] = 1 if x.status == 'show' else 0
285
            temp.append(temp_map)
286
            brandPrefMap[(x.brand).strip().upper()] = temp
287
 
288
    for x in session.query(user_actions).filter_by(user_id=userId).all():
289
        actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0
290
    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}).sort([('totalPoints',pymongo.DESCENDING),('bestSellerPoints',pymongo.DESCENDING),('nlcPoints',pymongo.DESCENDING),('rank',pymongo.DESCENDING)]))
291
    all_category_deals = []
292
    mobile_deals = []
293
    tablet_deals = []
294
    for deal in all_deals:
295
        if actionsMap.get(deal['_id']) == 0:
296
            fav_weight =.25
297
        elif actionsMap.get(deal['_id']) == 1:
298
            fav_weight = 1.5
299
        else:
300
            fav_weight = 1
301
 
302
        if brandPrefMap.get(deal['brand'].strip().upper()) is not None:
303
            brand_weight = 1
304
            for brandInfo in brandPrefMap.get(deal['brand'].strip().upper()):
305
                if brandInfo.get(deal['category_id']) is not None:
306
                    if brandInfo.get(deal['category_id']) == 1:
14055 kshitij.so 307
                        brand_weight = 2.0
14037 kshitij.so 308
        else:
309
            brand_weight = 1
310
 
311
        if pricePrefMap.get(deal['category_id']) is not None:
312
 
313
            if deal['available_price'] >= pricePrefMap.get(deal['category_id'])[0] and deal['available_price'] <= pricePrefMap.get(deal['category_id'])[1]:
314
                asp_weight = 1.5
315
            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]:
316
                asp_weight = 1.2
317
            else:
318
                asp_weight = 1
319
        else:
320
            asp_weight = 1
321
 
322
        persPoints = deal['totalPoints'] * fav_weight * brand_weight * asp_weight
323
        deal['persPoints'] = persPoints
324
 
325
        if deal['category_id'] ==3:
326
            mobile_deals.append(deal)
327
        elif deal['category_id'] ==5:
328
            tablet_deals.append(deal)
329
        else:
330
            continue
331
        all_category_deals.append(deal)
332
 
333
 
334
    mem_cache_val = {3:mobile_deals, 5:tablet_deals, 0:all_deals}
335
    mc.set(str(userId), mem_cache_val)
336
 
337
 
338
 
339
def getNewDeals(userId, category_id, offset, limit, sort, direction):
13922 kshitij.so 340
    if not bool(cashBackMap):
13921 kshitij.so 341
        populateCashBack()
14037 kshitij.so 342
 
13771 kshitij.so 343
    rank = 1
14037 kshitij.so 344
    dealsMap = {}
345
    user_specific_deals = mc.get(str(userId))
346
    if user_specific_deals is None:
347
        __populateCache(userId)
348
        user_specific_deals = mc.get(str(userId))
14038 kshitij.so 349
    else:
350
        print "Getting user deals from cache"
14037 kshitij.so 351
    category_specific_deals = user_specific_deals.get(category_id)
352
 
353
    if sort is None or direction is None:
354
        sorted_deals = sorted(category_specific_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
355
    else:
356
        if sort == "bestSellerPoints":
357
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['bestSellerPoints'], x['rank'], x['nlcPoints']),reverse=True)
358
        else:
359
            if direction == -1:
360
                rev = True
361
            else:
362
                rev = False
363
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['available_price']),reverse=rev)
364
 
365
    for d in sorted_deals[offset:offset+limit]:
366
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
367
        if not dealsMap.has_key(item[0]['identifier']):
368
            item[0]['dealRank'] = rank
369
            item[0]['persPoints'] = d['persPoints']
370
            try:
371
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
372
                if not cashBack or cashBack.get('cash_back_status')!=1:
373
                    item[0]['cash_back_type'] = 0
374
                    item[0]['cash_back'] = 0
375
                else:
376
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
377
                    item[0]['cash_back'] = cashBack['cash_back']
378
            except:
379
                print "Error in adding cashback to deals"
380
                item[0]['cash_back_type'] = 0
381
                item[0]['cash_back'] = 0
382
            dealsMap[item[0]['identifier']] = item[0]
383
 
384
            rank +=1
385
    return sorted(dealsMap.values(), key=itemgetter('dealRank'))
386
 
387
 
388
def getDeals(userId, category_id, offset, limit, sort, direction):
389
    if not bool(cashBackMap):
390
        populateCashBack()
391
    rank = 1
13771 kshitij.so 392
    deals = {}
13910 kshitij.so 393
    outer_query = []
394
    outer_query.append({"showDeal":1})
395
    query = {}
396
    query['$gt'] = 0
397
    outer_query.append({'totalPoints':query})
398
    if category_id in (3,5):
399
        outer_query.append({'category_id':category_id})
13803 kshitij.so 400
    if sort is None or direction is None:
401
        direct = -1
13910 kshitij.so 402
        print outer_query
403
        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 404
    else:
13910 kshitij.so 405
        print outer_query
13803 kshitij.so 406
        direct = direction
13910 kshitij.so 407
        if sort == "bestSellerPoints":
408
            print "yes,sorting by bestSellerPoints"
409
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
410
        else:
411
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 412
    for d in data:
413
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
414
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 415
            item[0]['dealRank'] = rank
416
            try:
417
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
418
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 419
                    item[0]['cash_back_type'] = 0
420
                    item[0]['cash_back'] = 0
13921 kshitij.so 421
                else:
13928 kshitij.so 422
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
423
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 424
            except:
425
                print "Error in adding cashback to deals"
13928 kshitij.so 426
                item[0]['cash_back_type'] = 0
427
                item[0]['cash_back'] = 0
13771 kshitij.so 428
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 429
 
13771 kshitij.so 430
            rank +=1
13785 kshitij.so 431
    return sorted(deals.values(), key=itemgetter('dealRank'))
432
 
433
def getItem(skuId):
14109 kshitij.so 434
    populateCashBack()
13795 kshitij.so 435
    try:
436
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
14107 kshitij.so 437
        for sku in skuData:
438
            try:
439
                cashBack = __getCashBack(sku['_id'], sku['source_id'], sku['category_id'])
14108 kshitij.so 440
                print "***"
441
                print cashBack
14107 kshitij.so 442
                if not cashBack or cashBack.get('cash_back_status')!=1:
443
                    sku['cash_back_type'] = 0
444
                    sku['cash_back'] = 0
445
                else:
446
                    sku['cash_back_type'] = cashBack['cash_back_type']
447
                    sku['cash_back'] = cashBack['cash_back']
448
            except:
449
                print "Error in adding cashback to deals"
450
                sku['cash_back_type'] = 0
451
                sku['cash_back'] = 0
13785 kshitij.so 452
        return skuData
13795 kshitij.so 453
    except:
454
        return [{}]
13836 kshitij.so 455
 
13921 kshitij.so 456
def __getCashBack(skuId, source_id, category_id):
457
    itemCashBack = itemCashBackMap.get(skuId)
458
    if itemCashBack is not None:
459
        return itemCashBack
460
 
461
    sourceCashBack = cashBackMap.get(source_id)
462
    if sourceCashBack is not None and len(sourceCashBack) > 0:
463
        for cashBack in sourceCashBack:
464
            if cashBack.get(category_id) is None:
465
                continue
466
            else:
467
                return cashBack.get(category_id)
468
    else:
469
        return {}
470
 
13836 kshitij.so 471
def getCashBackDetails(identifier, source_id):
13922 kshitij.so 472
    if not bool(cashBackMap):
13921 kshitij.so 473
        populateCashBack()
474
 
13836 kshitij.so 475
    """Need to add item level cashback, no data available right now."""
13771 kshitij.so 476
 
13921 kshitij.so 477
    if source_id in (1,2,4,5):
13839 kshitij.so 478
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 479
    elif source_id == 3:
13839 kshitij.so 480
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 481
    else:
482
        return {}
13836 kshitij.so 483
    if len(skuData) > 0:
13921 kshitij.so 484
 
485
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
486
        if itemCashBack is not None:
487
            return itemCashBack
488
 
489
        sourceCashBack = cashBackMap.get(source_id)
490
        if sourceCashBack is not None and len(sourceCashBack) > 0:
491
            for cashBack in sourceCashBack:
492
                if cashBack.get(skuData[0]['category_id']) is None:
493
                    continue
494
                else:
495
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 496
        else:
497
            return {} 
498
    else:
499
        return {}
13986 amit.gupta 500
 
501
 
502
def next_weekday(d, weekday):
503
    days_ahead = weekday - d.weekday()
504
    if days_ahead <= 0: # Target day already happened this week
505
        days_ahead += 7
506
    return d + timedelta(days_ahead)
507
 
13771 kshitij.so 508
 
13970 kshitij.so 509
def getAllDealerPrices(offset, limit):
510
    data = []
511
    collection = get_mongo_connection().Catalog.SkuDealerPrices
512
    cursor = collection.find().skip(offset).limit(limit)
513
    for val in cursor:
514
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
515
        if len(master) > 0:
14069 kshitij.so 516
            val['brand'] = master[0]['brand']
517
            val['source_product_name'] = master[0]['source_product_name']
518
            val['skuBundleId'] = master[0]['skuBundleId']
13970 kshitij.so 519
        else:
520
            val['brand'] = ""
521
            val['source_product_name'] = ""
522
            val['skuBundleId'] = ""
523
        data.append(val)
524
    return data
525
 
526
def addSkuDealerPrice(data):
527
    collection = get_mongo_connection().Catalog.SkuDealerPrices
528
    cursor = collection.find({"sku":data['sku']})
529
    if cursor.count() > 0:
530
        return {0:"Sku information already present."}
531
    else:
532
        collection.insert(data)
533
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
534
        return {1:"Data added successfully"}
535
 
536
def updateSkuDealerPrice(data, _id):
537
    try:
538
        collection = get_mongo_connection().Catalog.SkuDealerPrices
539
        collection.update({'_id':ObjectId(_id)},{"$set":{'dp':data['dp']}},upsert=False, multi = False)
540
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
541
        return {1:"Data updated successfully"}
542
    except:
543
        return {0:"Data not updated."}
544
 
545
def updateExceptionalNlc(data, _id):
546
    try:
547
        collection = get_mongo_connection().Catalog.ExceptionalNlc
548
        collection.update({'_id':ObjectId(_id)},{"$set":{'maxNlc':data['maxNlc'], 'minNlc':data['minNlc'], 'overrideNlc':data['overrideNlc']}},upsert=False, multi = False)
549
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
550
        return {1:"Data updated successfully"}
551
    except:
552
        return {0:"Data not updated."}
553
 
14041 kshitij.so 554
def resetCache(userId):
14043 kshitij.so 555
    try:
556
        mc.delete(userId)
557
        return {1:'Cache cleared.'}
558
    except:
559
        return {0:'Unable to clear cache.'}
560
 
14076 kshitij.so 561
def updateCollection(data):
14083 kshitij.so 562
    print data
14076 kshitij.so 563
    try:
564
        collection = get_mongo_connection().Catalog[data['class']]
565
        data.pop('class')
566
        _id = data.pop('oid')
14083 kshitij.so 567
        result = collection.update({'_id':ObjectId(_id)},{"$set":data},upsert=False, multi = False)
568
        print result
14076 kshitij.so 569
        #get_mongo_connection().Catalog.MasterData.update({'brand':data['brand'],'category_id':data['category_id']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
570
        return {1:"Data updated successfully"}
571
    except:
572
        return {0:"Data not updated."}
573
 
574
 
13970 kshitij.so 575
 
13572 kshitij.so 576
def main():
14038 kshitij.so 577
    x = getNewDeals(1, 0, 0, 500, None, None)
14037 kshitij.so 578
    for i in x:
579
        print i['_id'],
580
        print '\t',
581
        print i['persPoints']
13811 kshitij.so 582
 
13921 kshitij.so 583
 
13572 kshitij.so 584
if __name__=='__main__':
13932 amit.gupta 585
    main()