Subversion Repositories SmartDukaan

Rev

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

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