Subversion Repositories SmartDukaan

Rev

Rev 14507 | Rev 14550 | 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 = []
347
    activeFeaturedDeals = get_mongo_connection().Catalog.FeaturedDeals.find({'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())}})
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
359
    mc.set("featured_deals_category_"+str(0), all_category_fd)
360
    mc.set("featured_deals_category_"+str(3), mobile_fd)
361
    mc.set("featured_deals_category_"+str(5), tablet_fd)
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
 
14531 kshitij.so 367
    if mc.get("featured_deals_category_"+str(category_id)) is None:
368
        __populateFeaturedDeals() 
369
 
13771 kshitij.so 370
    rank = 1
14037 kshitij.so 371
    dealsMap = {}
372
    user_specific_deals = mc.get(str(userId))
373
    if user_specific_deals is None:
374
        __populateCache(userId)
375
        user_specific_deals = mc.get(str(userId))
14038 kshitij.so 376
    else:
377
        print "Getting user deals from cache"
14037 kshitij.so 378
    category_specific_deals = user_specific_deals.get(category_id)
379
 
380
    if sort is None or direction is None:
381
        sorted_deals = sorted(category_specific_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)
382
    else:
383
        if sort == "bestSellerPoints":
384
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['bestSellerPoints'], x['rank'], x['nlcPoints']),reverse=True)
385
        else:
386
            if direction == -1:
387
                rev = True
388
            else:
389
                rev = False
390
            sorted_deals = sorted(category_specific_deals, key = lambda x: (x['available_price']),reverse=rev)
391
 
392
    for d in sorted_deals[offset:offset+limit]:
393
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
394
        if not dealsMap.has_key(item[0]['identifier']):
395
            item[0]['dealRank'] = rank
396
            item[0]['persPoints'] = d['persPoints']
14322 kshitij.so 397
            if d['dealType'] == 1 and d['source_id'] ==1:
398
                item[0]['marketPlaceUrl'] = "http://www.amazon.in/dp/%s"%(item[0]['identifier'].strip()) 
14037 kshitij.so 399
            try:
400
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
401
                if not cashBack or cashBack.get('cash_back_status')!=1:
402
                    item[0]['cash_back_type'] = 0
403
                    item[0]['cash_back'] = 0
404
                else:
405
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
406
                    item[0]['cash_back'] = cashBack['cash_back']
407
            except:
408
                print "Error in adding cashback to deals"
409
                item[0]['cash_back_type'] = 0
410
                item[0]['cash_back'] = 0
411
            dealsMap[item[0]['identifier']] = item[0]
412
 
413
            rank +=1
414
    return sorted(dealsMap.values(), key=itemgetter('dealRank'))
415
 
416
 
417
def getDeals(userId, category_id, offset, limit, sort, direction):
418
    if not bool(cashBackMap):
419
        populateCashBack()
420
    rank = 1
13771 kshitij.so 421
    deals = {}
13910 kshitij.so 422
    outer_query = []
423
    outer_query.append({"showDeal":1})
424
    query = {}
425
    query['$gt'] = 0
426
    outer_query.append({'totalPoints':query})
427
    if category_id in (3,5):
428
        outer_query.append({'category_id':category_id})
13803 kshitij.so 429
    if sort is None or direction is None:
430
        direct = -1
13910 kshitij.so 431
        print outer_query
432
        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 433
    else:
13910 kshitij.so 434
        print outer_query
13803 kshitij.so 435
        direct = direction
13910 kshitij.so 436
        if sort == "bestSellerPoints":
437
            print "yes,sorting by bestSellerPoints"
438
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
439
        else:
440
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 441
    for d in data:
442
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
443
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 444
            item[0]['dealRank'] = rank
445
            try:
446
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
447
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 448
                    item[0]['cash_back_type'] = 0
449
                    item[0]['cash_back'] = 0
13921 kshitij.so 450
                else:
13928 kshitij.so 451
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
452
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 453
            except:
454
                print "Error in adding cashback to deals"
13928 kshitij.so 455
                item[0]['cash_back_type'] = 0
456
                item[0]['cash_back'] = 0
13771 kshitij.so 457
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 458
 
13771 kshitij.so 459
            rank +=1
13785 kshitij.so 460
    return sorted(deals.values(), key=itemgetter('dealRank'))
461
 
462
def getItem(skuId):
14113 kshitij.so 463
    if not bool(cashBackMap):
464
        populateCashBack()
13795 kshitij.so 465
    try:
466
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
14107 kshitij.so 467
        for sku in skuData:
468
            try:
469
                cashBack = __getCashBack(sku['_id'], sku['source_id'], sku['category_id'])
470
                if not cashBack or cashBack.get('cash_back_status')!=1:
471
                    sku['cash_back_type'] = 0
472
                    sku['cash_back'] = 0
473
                else:
474
                    sku['cash_back_type'] = cashBack['cash_back_type']
475
                    sku['cash_back'] = cashBack['cash_back']
476
            except:
477
                print "Error in adding cashback to deals"
478
                sku['cash_back_type'] = 0
479
                sku['cash_back'] = 0
13785 kshitij.so 480
        return skuData
13795 kshitij.so 481
    except:
482
        return [{}]
13836 kshitij.so 483
 
13921 kshitij.so 484
def __getCashBack(skuId, source_id, category_id):
485
    itemCashBack = itemCashBackMap.get(skuId)
486
    if itemCashBack is not None:
487
        return itemCashBack
488
 
489
    sourceCashBack = cashBackMap.get(source_id)
490
    if sourceCashBack is not None and len(sourceCashBack) > 0:
491
        for cashBack in sourceCashBack:
492
            if cashBack.get(category_id) is None:
493
                continue
494
            else:
495
                return cashBack.get(category_id)
496
    else:
497
        return {}
498
 
13836 kshitij.so 499
def getCashBackDetails(identifier, source_id):
13922 kshitij.so 500
    if not bool(cashBackMap):
13921 kshitij.so 501
        populateCashBack()
502
 
13836 kshitij.so 503
    """Need to add item level cashback, no data available right now."""
13771 kshitij.so 504
 
13921 kshitij.so 505
    if source_id in (1,2,4,5):
13839 kshitij.so 506
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 507
    elif source_id == 3:
13839 kshitij.so 508
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 509
    else:
510
        return {}
13836 kshitij.so 511
    if len(skuData) > 0:
13921 kshitij.so 512
 
513
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
514
        if itemCashBack is not None:
515
            return itemCashBack
516
 
517
        sourceCashBack = cashBackMap.get(source_id)
518
        if sourceCashBack is not None and len(sourceCashBack) > 0:
519
            for cashBack in sourceCashBack:
520
                if cashBack.get(skuData[0]['category_id']) is None:
521
                    continue
522
                else:
523
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 524
        else:
525
            return {} 
526
    else:
527
        return {}
13986 amit.gupta 528
 
14398 amit.gupta 529
def getImgSrc(identifier, source_id):
530
    skuData = None
531
    if source_id in (1,2,4,5):
14414 amit.gupta 532
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'identifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 533
    elif source_id == 3:
14414 amit.gupta 534
        skuData = get_mongo_connection().Catalog.MasterData.find_one({'secondaryIdentifier':identifier.strip(), 'source_id':source_id})
14398 amit.gupta 535
    if skuData is None:
536
        return {}
537
    else:
538
        return {'thumbnail':skuData.get('thumbnail')}
13986 amit.gupta 539
 
540
def next_weekday(d, weekday):
541
    days_ahead = weekday - d.weekday()
542
    if days_ahead <= 0: # Target day already happened this week
543
        days_ahead += 7
544
    return d + timedelta(days_ahead)
545
 
13771 kshitij.so 546
 
13970 kshitij.so 547
def getAllDealerPrices(offset, limit):
548
    data = []
549
    collection = get_mongo_connection().Catalog.SkuDealerPrices
550
    cursor = collection.find().skip(offset).limit(limit)
551
    for val in cursor:
552
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
553
        if len(master) > 0:
14069 kshitij.so 554
            val['brand'] = master[0]['brand']
555
            val['source_product_name'] = master[0]['source_product_name']
556
            val['skuBundleId'] = master[0]['skuBundleId']
13970 kshitij.so 557
        else:
558
            val['brand'] = ""
559
            val['source_product_name'] = ""
560
            val['skuBundleId'] = ""
561
        data.append(val)
562
    return data
563
 
564
def addSkuDealerPrice(data):
565
    collection = get_mongo_connection().Catalog.SkuDealerPrices
566
    cursor = collection.find({"sku":data['sku']})
567
    if cursor.count() > 0:
568
        return {0:"Sku information already present."}
569
    else:
570
        collection.insert(data)
571
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
572
        return {1:"Data added successfully"}
573
 
574
def updateSkuDealerPrice(data, _id):
575
    try:
576
        collection = get_mongo_connection().Catalog.SkuDealerPrices
577
        collection.update({'_id':ObjectId(_id)},{"$set":{'dp':data['dp']}},upsert=False, multi = False)
578
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
579
        return {1:"Data updated successfully"}
580
    except:
581
        return {0:"Data not updated."}
582
 
583
def updateExceptionalNlc(data, _id):
584
    try:
585
        collection = get_mongo_connection().Catalog.ExceptionalNlc
586
        collection.update({'_id':ObjectId(_id)},{"$set":{'maxNlc':data['maxNlc'], 'minNlc':data['minNlc'], 'overrideNlc':data['overrideNlc']}},upsert=False, multi = False)
587
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
588
        return {1:"Data updated successfully"}
589
    except:
590
        return {0:"Data not updated."}
591
 
14041 kshitij.so 592
def resetCache(userId):
14043 kshitij.so 593
    try:
594
        mc.delete(userId)
595
        return {1:'Cache cleared.'}
596
    except:
597
        return {0:'Unable to clear cache.'}
598
 
14076 kshitij.so 599
def updateCollection(data):
14083 kshitij.so 600
    print data
14076 kshitij.so 601
    try:
602
        collection = get_mongo_connection().Catalog[data['class']]
14322 kshitij.so 603
        class_name = data.pop('class')
604
        if class_name == "SkuSchemeDetails":
605
            data['addedOn'] = to_java_date(datetime.now())
14076 kshitij.so 606
        _id = data.pop('oid')
14083 kshitij.so 607
        result = collection.update({'_id':ObjectId(_id)},{"$set":data},upsert=False, multi = False)
14475 kshitij.so 608
        record = list(collection.find({'_id':ObjectId(_id)}))
14322 kshitij.so 609
        if class_name !="CategoryDiscount":
14475 kshitij.so 610
            get_mongo_connection().Catalog.MasterData.update({'_id':record[0]['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}})
14322 kshitij.so 611
        else:
14475 kshitij.so 612
            get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
14322 kshitij.so 613
                                                             {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
14076 kshitij.so 614
        return {1:"Data updated successfully"}
14475 kshitij.so 615
    except Exception as e:
616
        print e
14076 kshitij.so 617
        return {0:"Data not updated."}
618
 
14481 kshitij.so 619
def addNegativeDeals(data):
620
    collection = get_mongo_connection().Catalog.NegativeDeals
621
    cursor = collection.find({"sku":data['sku']})
622
    if cursor.count() > 0:
623
        return {0:"Sku information already present."}
624
    else:
625
        collection.insert(data)
626
        return {1:"Data added successfully"}
627
 
628
def getAllNegativeDeals(offset, limit):
629
    data = []
630
    collection = get_mongo_connection().Catalog.NegativeDeals
631
    cursor = collection.find().skip(offset).limit(limit)
632
    for val in cursor:
633
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
634
        if len(master) > 0:
635
            val['brand'] = master[0]['brand']
636
            val['source_product_name'] = master[0]['source_product_name']
637
            val['skuBundleId'] = master[0]['skuBundleId']
638
        else:
639
            val['brand'] = ""
640
            val['source_product_name'] = ""
641
            val['skuBundleId'] = ""
642
        data.append(val)
643
    return data
644
 
645
def getAllManualDeals(offset, limit):
646
    data = []
647
    collection = get_mongo_connection().Catalog.ManualDeals
14495 kshitij.so 648
    cursor = collection.find({'endDate':{'$gte':to_java_date(datetime.now())}}).skip(offset).limit(limit)
14481 kshitij.so 649
    for val in cursor:
650
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
651
        if len(master) > 0:
652
            val['brand'] = master[0]['brand']
653
            val['source_product_name'] = master[0]['source_product_name']
654
            val['skuBundleId'] = master[0]['skuBundleId']
655
        else:
656
            val['brand'] = ""
657
            val['source_product_name'] = ""
658
            val['skuBundleId'] = ""
659
        data.append(val)
660
    return data
14076 kshitij.so 661
 
14481 kshitij.so 662
def addManualDeal(data):
663
    collection = get_mongo_connection().Catalog.ManualDeals
14495 kshitij.so 664
    cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
14481 kshitij.so 665
    if cursor.count() > 0:
666
        return {0:"Sku information already present."}
667
    else:
668
        collection.insert(data)
669
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
670
        return {1:"Data added successfully"}
671
 
672
def deleteDocument(data):
673
    print data
674
    try:
675
        collection = get_mongo_connection().Catalog[data['class']]
676
        class_name = data.pop('class')
677
        _id = data.pop('oid')
678
        record = list(collection.find({'_id':ObjectId(_id)}))
679
        collection.remove({'_id':ObjectId(_id)})
680
        if class_name !="CategoryDiscount":
681
            get_mongo_connection().Catalog.MasterData.update({'_id':record[0]['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}})
682
        else:
683
            get_mongo_connection().Catalog.MasterData.update({'brand':re.compile(record[0]['brand'], re.IGNORECASE),'category_id':record[0]['category_id']}, \
684
                                                             {"$set":{'updatedOn':to_java_date(datetime.now())}},upsert=False,multi=True)
685
        return {1:"Document deleted successfully"}
686
    except Exception as e:
687
        print e
688
        return {0:"Document not deleted."}
13970 kshitij.so 689
 
14482 kshitij.so 690
def searchMaster(offset, limit, search_term):
691
    data = []
14531 kshitij.so 692
    if search_term is not None:
693
        try:
694
            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)
695
            for record in collection:
696
                data.append(record)
697
        except:
698
            pass
699
    else:
700
        collection = get_mongo_connection().Catalog.MasterData.find({'source_id':{'$in':SOURCE_MAP.keys()}}).skip(offset).limit(limit)
14482 kshitij.so 701
        for record in collection:
702
            data.append(record)
703
    return data
14481 kshitij.so 704
 
14495 kshitij.so 705
def getAllFeaturedDeals(offset, limit):
706
    data = []
707
    collection = get_mongo_connection().Catalog.FeaturedDeals
708
    cursor = collection.find({'endDate':{'$gte':to_java_date(datetime.now())}}).skip(offset).limit(limit)
709
    for val in cursor:
710
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
711
        if len(master) > 0:
712
            val['brand'] = master[0]['brand']
713
            val['source_product_name'] = master[0]['source_product_name']
714
            val['skuBundleId'] = master[0]['skuBundleId']
715
        else:
716
            val['brand'] = ""
717
            val['source_product_name'] = ""
718
            val['skuBundleId'] = ""
719
        data.append(val)
720
    return data
721
 
722
def addFeaturedDeal(data):
14507 kshitij.so 723
    collection = get_mongo_connection().Catalog.FeaturedDeals
14495 kshitij.so 724
    cursor = collection.find({'sku':data['sku'],'startDate':{'$lte':data['startDate']},'endDate':{'$gte':data['endDate']}})
725
    if cursor.count() > 0:
726
        return {0:"Sku information already present."}
727
    else:
728
        collection.insert(data)
729
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
730
        return {1:"Data added successfully"}
731
 
14499 kshitij.so 732
def searchCollection(class_name, sku, skuBundleId):
14497 kshitij.so 733
    data = []
734
    collection = get_mongo_connection().Catalog[class_name]
14499 kshitij.so 735
    if sku is not None:
736
        cursor = collection.find({'sku':sku})
737
        for val in cursor:
738
            master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
739
            if len(master) > 0:
740
                val['brand'] = master[0]['brand']
741
                val['source_product_name'] = master[0]['source_product_name']
742
                val['skuBundleId'] = master[0]['skuBundleId']
743
            else:
744
                val['brand'] = ""
745
                val['source_product_name'] = ""
746
                val['skuBundleId'] = ""
747
            data.append(val)
748
        return data
749
    else:
750
        skuIds = get_mongo_connection().MasterData.find({'skuBundleId':skuBundleId}).distinct('_id')
751
        for sku in skuIds:
752
            cursor = collection.find({'sku':sku})
753
            for val in cursor:
754
                master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
755
                if len(master) > 0:
756
                    val['brand'] = master[0]['brand']
757
                    val['source_product_name'] = master[0]['source_product_name']
758
                    val['skuBundleId'] = master[0]['skuBundleId']
759
                else:
760
                    val['brand'] = ""
761
                    val['source_product_name'] = ""
762
                    val['skuBundleId'] = ""
763
                data.append(val)
764
        return data
14495 kshitij.so 765
 
13572 kshitij.so 766
def main():
14531 kshitij.so 767
    print searchMaster(0, 10, "")
13811 kshitij.so 768
 
13921 kshitij.so 769
 
13572 kshitij.so 770
if __name__=='__main__':
13932 amit.gupta 771
    main()