Subversion Repositories SmartDukaan

Rev

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

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