Subversion Repositories SmartDukaan

Rev

Rev 14531 | Rev 14551 | 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
 
95
def addSchemeDetailsForSku(data):
13970 kshitij.so 96
    collection = get_mongo_connection().Catalog.SkuSchemeDetails
13572 kshitij.so 97
    data['addedOn'] = to_java_date(datetime.now())
98
    collection.insert(data)
13639 kshitij.so 99
    return {1:"Data added successfully"}
13572 kshitij.so 100
 
14069 kshitij.so 101
def getAllSkuWiseSchemeDetails(offset, limit):
13572 kshitij.so 102
    data = []
13970 kshitij.so 103
    collection = get_mongo_connection().Catalog.SkuSchemeDetails
14071 kshitij.so 104
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 105
    for val in cursor:
14069 kshitij.so 106
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
107
        if len(master) > 0:
108
            val['brand'] = master[0]['brand']
109
            val['source_product_name'] = master[0]['source_product_name']
110
            val['skuBundleId'] = master[0]['skuBundleId']
111
        else:
112
            val['brand'] = ""
113
            val['source_product_name'] = ""
114
            val['skuBundleId'] = ""
13572 kshitij.so 115
        data.append(val)
116
    return data
117
 
118
def addSkuDiscountInfo(data):
13970 kshitij.so 119
    collection = get_mongo_connection().Catalog.SkuDiscountInfo
13572 kshitij.so 120
    cursor = collection.find({"sku":data['sku']})
13642 kshitij.so 121
    if cursor.count() > 0:
13639 kshitij.so 122
        return {0:"Sku information already present."}
13572 kshitij.so 123
    else:
124
        collection.insert(data)
13970 kshitij.so 125
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
13639 kshitij.so 126
        return {1:"Data added successfully"}
13572 kshitij.so 127
 
13970 kshitij.so 128
def getallSkuDiscountInfo(offset, limit):
13572 kshitij.so 129
    data = []
13970 kshitij.so 130
    collection = get_mongo_connection().Catalog.SkuDiscountInfo
131
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 132
    for val in cursor:
13970 kshitij.so 133
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
134
        if len(master) > 0:
14069 kshitij.so 135
            val['brand'] = master[0]['brand']
136
            val['source_product_name'] = master[0]['source_product_name']
137
            val['skuBundleId'] = master[0]['skuBundleId']
13970 kshitij.so 138
        else:
139
            val['brand'] = ""
140
            val['source_product_name'] = ""
141
            val['skuBundleId'] = ""
13572 kshitij.so 142
        data.append(val)
143
    return data
144
 
13970 kshitij.so 145
def updateSkuDiscount(data,_id):
146
    try:
147
        collection = get_mongo_connection().Catalog.SkuDiscountInfo
148
        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)
149
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
150
        return {1:"Data updated successfully"}
151
    except:
152
        return {0:"Data not updated."}
153
 
154
 
13572 kshitij.so 155
def addExceptionalNlc(data):
13970 kshitij.so 156
    collection = get_mongo_connection().Catalog.ExceptionalNlc
13572 kshitij.so 157
    cursor = collection.find({"sku":data['sku']})
13642 kshitij.so 158
    if cursor.count() > 0:
13639 kshitij.so 159
        return {0:"Sku information already present."}
13572 kshitij.so 160
    else:
161
        collection.insert(data)
13970 kshitij.so 162
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
13639 kshitij.so 163
        return {1:"Data added successfully"}
13572 kshitij.so 164
 
13970 kshitij.so 165
def getAllExceptionlNlcItems(offset, limit):
13572 kshitij.so 166
    data = []
13970 kshitij.so 167
    collection = get_mongo_connection().Catalog.ExceptionalNlc
14071 kshitij.so 168
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 169
    for val in cursor:
13970 kshitij.so 170
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
171
        if len(master) > 0:
14069 kshitij.so 172
            val['brand'] = master[0]['brand']
173
            val['source_product_name'] = master[0]['source_product_name']
174
            val['skuBundleId'] = master[0]['skuBundleId']
13970 kshitij.so 175
        else:
176
            val['brand'] = ""
177
            val['source_product_name'] = ""
178
            val['skuBundleId'] = ""
13572 kshitij.so 179
        data.append(val)
180
    return data
181
 
14005 amit.gupta 182
def getMerchantOrdersByUser(userId, page=1, window=50, searchMap={}):
183
    if searchMap is None:
184
        searchMap = {}
13603 amit.gupta 185
    if page==None:
186
        page = 1
187
 
188
    if window==None:
189
        window = 50
190
    result = {}
13582 amit.gupta 191
    skip = (page-1)*window
14005 amit.gupta 192
 
14353 amit.gupta 193
    if userId is not None:
194
        searchMap['userId'] = userId
13603 amit.gupta 195
    collection = get_mongo_connection().Dtr.merchantOrder
14005 amit.gupta 196
    cursor = collection.find(searchMap).sort("_id",-1)
13603 amit.gupta 197
    total_count = cursor.count()
198
    pages = total_count/window + (0 if total_count%window==0 else 1)  
199
    print "total_count", total_count
200
    if total_count > skip:
13999 amit.gupta 201
        cursor = cursor.skip(skip).limit(window)
13603 amit.gupta 202
        orders = []
203
        for order in cursor:
14002 amit.gupta 204
            del(order["_id"])
205
            orders.append(order)
13603 amit.gupta 206
        result['data'] = orders
207
        result['window'] = window
208
        result['totalCount'] = total_count 
209
        result['currCount'] = cursor.count()
210
        result['totalPages'] = pages
211
        result['currPage'] = page    
212
        return result
213
    else:
214
        return result
13630 kshitij.so 215
 
13927 amit.gupta 216
def getRefunds(userId, page=1, window=10):
217
    if page==None:
218
        page = 1
219
 
220
    if window==None:
13995 amit.gupta 221
        window = 10
13927 amit.gupta 222
    result = {}
223
    skip = (page-1)*window
224
    collection = get_mongo_connection().Dtr.refund
225
    cursor = collection.find({"userId":userId})
226
    total_count = cursor.count()
227
    pages = total_count/window + (0 if total_count%window==0 else 1)  
228
    print "total_count", total_count
229
    if total_count > skip:
13991 amit.gupta 230
        cursor = cursor.skip(skip).limit(window).sort([('batchId',-1)])
13927 amit.gupta 231
        refunds = []
232
        for refund in cursor:
233
            del(refund["_id"])
234
            refunds.append(refund)
235
        result['data'] = refunds
236
        result['window'] = window
237
        result['totalCount'] = total_count 
238
        result['currCount'] = cursor.count()
239
        result['totalPages'] = pages
240
        result['currPage'] = page    
241
        return result
242
    else:
243
        return result
244
 
245
def getPendingRefunds(userId):
13991 amit.gupta 246
    print type(userId)
13927 amit.gupta 247
    result = get_mongo_connection().Dtr.merchantOrder\
248
        .aggregate([
249
                    {'$match':{'subOrders.cashBackStatus':Store.CB_APPROVED, 'userId':userId}},
250
                    {'$unwind':"$subOrders"},
251
                    { 
252
                     '$group':{
253
                               '_id':None,
254
                               'amount': { '$sum':'$subOrders.cashBackAmount'},
255
                               }
256
                     }
13987 amit.gupta 257
                ])['result']
258
 
259
    if len(result)>0:
260
        result = result[0]        
261
        result.pop("_id")
262
    else:
263
        result={}
264
        result['amount'] = 0.0
14305 amit.gupta 265
    result['nextCredit'] = datetime.strftime(next_weekday(datetime.now(), int(PythonPropertyReader.getConfig('CREDIT_DAY_OF_WEEK'))),"%Y-%m-%d %H:%M:%S")
13927 amit.gupta 266
    return result
14037 kshitij.so 267
 
268
def __populateCache(userId):
269
    print "Populating memcache for userId",userId
270
    outer_query = []
271
    outer_query.append({"showDeal":1})
272
    query = {}
273
    query['$gt'] = 0
274
    outer_query.append({'totalPoints':query})
275
    brandPrefMap = {}
276
    pricePrefMap = {}
277
    actionsMap = {}
278
    brand_p = session.query(price_preferences).filter_by(user_id=userId).all()
279
    for x in brand_p:
280
        pricePrefMap[x.category_id] = [x.min_price,x.max_price]
281
    for x in session.query(brand_preferences).filter_by(user_id=userId).all():
282
        temp_map = {}
283
        if brandPrefMap.has_key((x.brand).strip().upper()):
284
            val = brandPrefMap.get((x.brand).strip().upper())
285
            temp_map[x.category_id] = 1 if x.status == 'show' else 0
286
            val.append(temp_map)
287
        else:
288
            temp = []
289
            temp_map[x.category_id] = 1 if x.status == 'show' else 0
290
            temp.append(temp_map)
291
            brandPrefMap[(x.brand).strip().upper()] = temp
292
 
293
    for x in session.query(user_actions).filter_by(user_id=userId).all():
294
        actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0
14323 kshitij.so 295
    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 296
    all_category_deals = []
297
    mobile_deals = []
298
    tablet_deals = []
299
    for deal in all_deals:
300
        if actionsMap.get(deal['_id']) == 0:
301
            fav_weight =.25
302
        elif actionsMap.get(deal['_id']) == 1:
303
            fav_weight = 1.5
304
        else:
305
            fav_weight = 1
306
 
307
        if brandPrefMap.get(deal['brand'].strip().upper()) is not None:
308
            brand_weight = 1
309
            for brandInfo in brandPrefMap.get(deal['brand'].strip().upper()):
310
                if brandInfo.get(deal['category_id']) is not None:
311
                    if brandInfo.get(deal['category_id']) == 1:
14055 kshitij.so 312
                        brand_weight = 2.0
14037 kshitij.so 313
        else:
314
            brand_weight = 1
315
 
316
        if pricePrefMap.get(deal['category_id']) is not None:
317
 
318
            if deal['available_price'] >= pricePrefMap.get(deal['category_id'])[0] and deal['available_price'] <= pricePrefMap.get(deal['category_id'])[1]:
319
                asp_weight = 1.5
320
            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]:
321
                asp_weight = 1.2
322
            else:
323
                asp_weight = 1
324
        else:
325
            asp_weight = 1
326
 
327
        persPoints = deal['totalPoints'] * fav_weight * brand_weight * asp_weight
328
        deal['persPoints'] = persPoints
329
 
330
        if deal['category_id'] ==3:
331
            mobile_deals.append(deal)
332
        elif deal['category_id'] ==5:
333
            tablet_deals.append(deal)
334
        else:
335
            continue
336
        all_category_deals.append(deal)
337
 
14144 kshitij.so 338
    session.close()
14037 kshitij.so 339
    mem_cache_val = {3:mobile_deals, 5:tablet_deals, 0:all_deals}
340
    mc.set(str(userId), mem_cache_val)
341
 
342
 
14531 kshitij.so 343
def __populateFeaturedDeals():
344
    all_category_fd = []
345
    mobile_fd = []
346
    tablet_fd = []
14550 kshitij.so 347
    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 348
    for activeFeaturedDeal in activeFeaturedDeals:
349
        for k,v in activeFeaturedDeal['rankDetails']:
350
            featuredDeal = FeaturedDeals(activeFeaturedDeal['sku'], int(k), activeFeaturedDeal['thresholdPrice'], int(v))
351
            if featuredDeal.category_id == 0:
352
                all_category_fd.append(featuredDeal)
353
            elif featuredDeal.category_id == 3:
354
                mobile_fd.append(featuredDeal)
355
            elif featuredDeal.category_id == 5:
356
                tablet_fd.append(featuredDeal)
357
            else:
358
                continue
14550 kshitij.so 359
    mc.set("featured_deals_category_"+str(0), all_category_fd, 3600)
360
    mc.set("featured_deals_category_"+str(3), mobile_fd, 3600)
361
    mc.set("featured_deals_category_"+str(5), tablet_fd, 3600)
14037 kshitij.so 362
 
363
def getNewDeals(userId, category_id, offset, limit, sort, direction):
13922 kshitij.so 364
    if not bool(cashBackMap):
13921 kshitij.so 365
        populateCashBack()
14037 kshitij.so 366
 
14550 kshitij.so 367
    try:
368
        if mc.get("featured_deals_category_"+str(category_id)) is None:
369
            __populateFeaturedDeals()
370
    except:
371
        pass 
14531 kshitij.so 372
 
13771 kshitij.so 373
    rank = 1
14037 kshitij.so 374
    dealsMap = {}
375
    user_specific_deals = mc.get(str(userId))
376
    if user_specific_deals is None:
377
        __populateCache(userId)
378
        user_specific_deals = mc.get(str(userId))
14038 kshitij.so 379
    else:
380
        print "Getting user deals from cache"
14037 kshitij.so 381
    category_specific_deals = user_specific_deals.get(category_id)
382
 
383
    if sort is None or direction is None:
384
        sorted_deals = sorted(category_specific_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
385
    else:
386
        if sort == "bestSellerPoints":
387
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['bestSellerPoints'], x['rank'], x['nlcPoints']),reverse=True)
388
        else:
389
            if direction == -1:
390
                rev = True
391
            else:
392
                rev = False
393
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['available_price']),reverse=rev)
394
 
395
    for d in sorted_deals[offset:offset+limit]:
396
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
397
        if not dealsMap.has_key(item[0]['identifier']):
398
            item[0]['dealRank'] = rank
399
            item[0]['persPoints'] = d['persPoints']
14322 kshitij.so 400
            if d['dealType'] == 1 and d['source_id'] ==1:
401
                item[0]['marketPlaceUrl'] = "http://www.amazon.in/dp/%s"%(item[0]['identifier'].strip()) 
14037 kshitij.so 402
            try:
403
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
404
                if not cashBack or cashBack.get('cash_back_status')!=1:
405
                    item[0]['cash_back_type'] = 0
406
                    item[0]['cash_back'] = 0
407
                else:
408
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
409
                    item[0]['cash_back'] = cashBack['cash_back']
410
            except:
411
                print "Error in adding cashback to deals"
412
                item[0]['cash_back_type'] = 0
413
                item[0]['cash_back'] = 0
414
            dealsMap[item[0]['identifier']] = item[0]
415
 
416
            rank +=1
417
    return sorted(dealsMap.values(), key=itemgetter('dealRank'))
418
 
419
 
420
def getDeals(userId, category_id, offset, limit, sort, direction):
421
    if not bool(cashBackMap):
422
        populateCashBack()
423
    rank = 1
13771 kshitij.so 424
    deals = {}
13910 kshitij.so 425
    outer_query = []
426
    outer_query.append({"showDeal":1})
427
    query = {}
428
    query['$gt'] = 0
429
    outer_query.append({'totalPoints':query})
430
    if category_id in (3,5):
431
        outer_query.append({'category_id':category_id})
13803 kshitij.so 432
    if sort is None or direction is None:
433
        direct = -1
13910 kshitij.so 434
        print outer_query
435
        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 436
    else:
13910 kshitij.so 437
        print outer_query
13803 kshitij.so 438
        direct = direction
13910 kshitij.so 439
        if sort == "bestSellerPoints":
440
            print "yes,sorting by bestSellerPoints"
441
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
442
        else:
443
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 444
    for d in data:
445
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
446
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 447
            item[0]['dealRank'] = rank
448
            try:
449
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
450
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 451
                    item[0]['cash_back_type'] = 0
452
                    item[0]['cash_back'] = 0
13921 kshitij.so 453
                else:
13928 kshitij.so 454
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
455
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 456
            except:
457
                print "Error in adding cashback to deals"
13928 kshitij.so 458
                item[0]['cash_back_type'] = 0
459
                item[0]['cash_back'] = 0
13771 kshitij.so 460
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 461
 
13771 kshitij.so 462
            rank +=1
13785 kshitij.so 463
    return sorted(deals.values(), key=itemgetter('dealRank'))
464
 
465
def getItem(skuId):
14113 kshitij.so 466
    if not bool(cashBackMap):
467
        populateCashBack()
13795 kshitij.so 468
    try:
469
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
14107 kshitij.so 470
        for sku in skuData:
471
            try:
472
                cashBack = __getCashBack(sku['_id'], sku['source_id'], sku['category_id'])
473
                if not cashBack or cashBack.get('cash_back_status')!=1:
474
                    sku['cash_back_type'] = 0
475
                    sku['cash_back'] = 0
476
                else:
477
                    sku['cash_back_type'] = cashBack['cash_back_type']
478
                    sku['cash_back'] = cashBack['cash_back']
479
            except:
480
                print "Error in adding cashback to deals"
481
                sku['cash_back_type'] = 0
482
                sku['cash_back'] = 0
13785 kshitij.so 483
        return skuData
13795 kshitij.so 484
    except:
485
        return [{}]
13836 kshitij.so 486
 
13921 kshitij.so 487
def __getCashBack(skuId, source_id, category_id):
488
    itemCashBack = itemCashBackMap.get(skuId)
489
    if itemCashBack is not None:
490
        return itemCashBack
491
 
492
    sourceCashBack = cashBackMap.get(source_id)
493
    if sourceCashBack is not None and len(sourceCashBack) > 0:
494
        for cashBack in sourceCashBack:
495
            if cashBack.get(category_id) is None:
496
                continue
497
            else:
498
                return cashBack.get(category_id)
499
    else:
500
        return {}
501
 
13836 kshitij.so 502
def getCashBackDetails(identifier, source_id):
13922 kshitij.so 503
    if not bool(cashBackMap):
13921 kshitij.so 504
        populateCashBack()
505
 
13836 kshitij.so 506
    """Need to add item level cashback, no data available right now."""
13771 kshitij.so 507
 
13921 kshitij.so 508
    if source_id in (1,2,4,5):
13839 kshitij.so 509
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 510
    elif source_id == 3:
13839 kshitij.so 511
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 512
    else:
513
        return {}
13836 kshitij.so 514
    if len(skuData) > 0:
13921 kshitij.so 515
 
516
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
517
        if itemCashBack is not None:
518
            return itemCashBack
519
 
520
        sourceCashBack = cashBackMap.get(source_id)
521
        if sourceCashBack is not None and len(sourceCashBack) > 0:
522
            for cashBack in sourceCashBack:
523
                if cashBack.get(skuData[0]['category_id']) is None:
524
                    continue
525
                else:
526
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 527
        else:
528
            return {} 
529
    else:
530
        return {}
13986 amit.gupta 531
 
14398 amit.gupta 532
def getImgSrc(identifier, source_id):
533
    skuData = None
534
    if source_id in (1,2,4,5):
14414 amit.gupta 535
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'identifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 536
    elif source_id == 3:
14414 amit.gupta 537
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'secondaryIdentifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 538
    if skuData is None:
539
        return {}
540
    else:
541
        return {'thumbnail':skuData.get('thumbnail')}
13986 amit.gupta 542
 
543
def next_weekday(d, weekday):
544
    days_ahead = weekday - d.weekday()
545
    if days_ahead <= 0: # Target day already happened this week
546
        days_ahead += 7
547
    return d + timedelta(days_ahead)
548
 
13771 kshitij.so 549
 
13970 kshitij.so 550
def getAllDealerPrices(offset, limit):
551
    data = []
552
    collection = get_mongo_connection().Catalog.SkuDealerPrices
553
    cursor = collection.find().skip(offset).limit(limit)
554
    for val in cursor:
555
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
556
        if len(master) > 0:
14069 kshitij.so 557
            val['brand'] = master[0]['brand']
558
            val['source_product_name'] = master[0]['source_product_name']
559
            val['skuBundleId'] = master[0]['skuBundleId']
13970 kshitij.so 560
        else:
561
            val['brand'] = ""
562
            val['source_product_name'] = ""
563
            val['skuBundleId'] = ""
564
        data.append(val)
565
    return data
566
 
567
def addSkuDealerPrice(data):
568
    collection = get_mongo_connection().Catalog.SkuDealerPrices
569
    cursor = collection.find({"sku":data['sku']})
570
    if cursor.count() > 0:
571
        return {0:"Sku information already present."}
572
    else:
573
        collection.insert(data)
574
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
575
        return {1:"Data added successfully"}
576
 
577
def updateSkuDealerPrice(data, _id):
578
    try:
579
        collection = get_mongo_connection().Catalog.SkuDealerPrices
580
        collection.update({'_id':ObjectId(_id)},{"$set":{'dp':data['dp']}},upsert=False, multi = False)
581
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
582
        return {1:"Data updated successfully"}
583
    except:
584
        return {0:"Data not updated."}
585
 
586
def updateExceptionalNlc(data, _id):
587
    try:
588
        collection = get_mongo_connection().Catalog.ExceptionalNlc
589
        collection.update({'_id':ObjectId(_id)},{"$set":{'maxNlc':data['maxNlc'], 'minNlc':data['minNlc'], 'overrideNlc':data['overrideNlc']}},upsert=False, multi = False)
590
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
591
        return {1:"Data updated successfully"}
592
    except:
593
        return {0:"Data not updated."}
594
 
14041 kshitij.so 595
def resetCache(userId):
14043 kshitij.so 596
    try:
597
        mc.delete(userId)
598
        return {1:'Cache cleared.'}
599
    except:
600
        return {0:'Unable to clear cache.'}
601
 
14076 kshitij.so 602
def updateCollection(data):
14083 kshitij.so 603
    print data
14076 kshitij.so 604
    try:
605
        collection = get_mongo_connection().Catalog[data['class']]
14322 kshitij.so 606
        class_name = data.pop('class')
607
        if class_name == "SkuSchemeDetails":
608
            data['addedOn'] = to_java_date(datetime.now())
14076 kshitij.so 609
        _id = data.pop('oid')
14083 kshitij.so 610
        result = collection.update({'_id':ObjectId(_id)},{"$set":data},upsert=False, multi = False)
14475 kshitij.so 611
        record = list(collection.find({'_id':ObjectId(_id)}))
14322 kshitij.so 612
        if class_name !="CategoryDiscount":
14475 kshitij.so 613
            get_mongo_connection().Catalog.MasterData.update({'_id':record[0]['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}})
14322 kshitij.so 614
        else:
14475 kshitij.so 615
            get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
14322 kshitij.so 616
                                                             {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
14076 kshitij.so 617
        return {1:"Data updated successfully"}
14475 kshitij.so 618
    except Exception as e:
619
        print e
14076 kshitij.so 620
        return {0:"Data not updated."}
621
 
14481 kshitij.so 622
def addNegativeDeals(data):
623
    collection = get_mongo_connection().Catalog.NegativeDeals
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
        return {1:"Data added successfully"}
630
 
631
def getAllNegativeDeals(offset, limit):
632
    data = []
633
    collection = get_mongo_connection().Catalog.NegativeDeals
634
    cursor = collection.find().skip(offset).limit(limit)
635
    for val in cursor:
636
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
637
        if len(master) > 0:
638
            val['brand'] = master[0]['brand']
639
            val['source_product_name'] = master[0]['source_product_name']
640
            val['skuBundleId'] = master[0]['skuBundleId']
641
        else:
642
            val['brand'] = ""
643
            val['source_product_name'] = ""
644
            val['skuBundleId'] = ""
645
        data.append(val)
646
    return data
647
 
648
def getAllManualDeals(offset, limit):
649
    data = []
650
    collection = get_mongo_connection().Catalog.ManualDeals
14495 kshitij.so 651
    cursor = collection.find({'endDate':{'$gte':to_java_date(datetime.now())}}).skip(offset).limit(limit)
14481 kshitij.so 652
    for val in cursor:
653
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
654
        if len(master) > 0:
655
            val['brand'] = master[0]['brand']
656
            val['source_product_name'] = master[0]['source_product_name']
657
            val['skuBundleId'] = master[0]['skuBundleId']
658
        else:
659
            val['brand'] = ""
660
            val['source_product_name'] = ""
661
            val['skuBundleId'] = ""
662
        data.append(val)
663
    return data
14076 kshitij.so 664
 
14481 kshitij.so 665
def addManualDeal(data):
666
    collection = get_mongo_connection().Catalog.ManualDeals
14495 kshitij.so 667
    cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
14481 kshitij.so 668
    if cursor.count() > 0:
669
        return {0:"Sku information already present."}
670
    else:
671
        collection.insert(data)
672
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
673
        return {1:"Data added successfully"}
674
 
675
def deleteDocument(data):
676
    print data
677
    try:
678
        collection = get_mongo_connection().Catalog[data['class']]
679
        class_name = data.pop('class')
680
        _id = data.pop('oid')
681
        record = list(collection.find({'_id':ObjectId(_id)}))
682
        collection.remove({'_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:"Document deleted successfully"}
689
    except Exception as e:
690
        print e
691
        return {0:"Document not deleted."}
13970 kshitij.so 692
 
14482 kshitij.so 693
def searchMaster(offset, limit, search_term):
694
    data = []
14531 kshitij.so 695
    if search_term is not None:
696
        try:
697
            collection = get_mongo_connection().Catalog.MasterData.find({'source_product_name':re.compile(search_term, re.IGNORECASE),'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
698
            for record in collection:
699
                data.append(record)
700
        except:
701
            pass
702
    else:
703
        collection = get_mongo_connection().Catalog.MasterData.find({'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
14482 kshitij.so 704
        for record in collection:
705
            data.append(record)
706
    return data
14481 kshitij.so 707
 
14495 kshitij.so 708
def getAllFeaturedDeals(offset, limit):
709
    data = []
710
    collection = get_mongo_connection().Catalog.FeaturedDeals
711
    cursor = collection.find({'endDate':{'$gte':to_java_date(datetime.now())}}).skip(offset).limit(limit)
712
    for val in cursor:
713
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
714
        if len(master) > 0:
715
            val['brand'] = master[0]['brand']
716
            val['source_product_name'] = master[0]['source_product_name']
717
            val['skuBundleId'] = master[0]['skuBundleId']
718
        else:
719
            val['brand'] = ""
720
            val['source_product_name'] = ""
721
            val['skuBundleId'] = ""
722
        data.append(val)
723
    return data
724
 
725
def addFeaturedDeal(data):
14507 kshitij.so 726
    collection = get_mongo_connection().Catalog.FeaturedDeals
14495 kshitij.so 727
    cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
728
    if cursor.count() > 0:
729
        return {0:"Sku information already present."}
730
    else:
731
        collection.insert(data)
732
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
733
        return {1:"Data added successfully"}
734
 
14499 kshitij.so 735
def searchCollection(class_name, sku, skuBundleId):
14497 kshitij.so 736
    data = []
737
    collection = get_mongo_connection().Catalog[class_name]
14499 kshitij.so 738
    if sku is not None:
739
        cursor = collection.find({'sku':sku})
740
        for val in cursor:
741
            master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
742
            if len(master) > 0:
743
                val['brand'] = master[0]['brand']
744
                val['source_product_name'] = master[0]['source_product_name']
745
                val['skuBundleId'] = master[0]['skuBundleId']
746
            else:
747
                val['brand'] = ""
748
                val['source_product_name'] = ""
749
                val['skuBundleId'] = ""
750
            data.append(val)
751
        return data
752
    else:
753
        skuIds = get_mongo_connection().MasterData.find({'skuBundleId':skuBundleId}).distinct('_id')
754
        for sku in skuIds:
755
            cursor = collection.find({'sku':sku})
756
            for val in cursor:
757
                master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
758
                if len(master) > 0:
759
                    val['brand'] = master[0]['brand']
760
                    val['source_product_name'] = master[0]['source_product_name']
761
                    val['skuBundleId'] = master[0]['skuBundleId']
762
                else:
763
                    val['brand'] = ""
764
                    val['source_product_name'] = ""
765
                    val['skuBundleId'] = ""
766
                data.append(val)
767
        return data
14495 kshitij.so 768
 
13572 kshitij.so 769
def main():
14550 kshitij.so 770
    print searchMaster(0, 10, "iphone 5")
13811 kshitij.so 771
 
13921 kshitij.so 772
 
13572 kshitij.so 773
if __name__=='__main__':
13932 amit.gupta 774
    main()