Subversion Repositories SmartDukaan

Rev

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