Subversion Repositories SmartDukaan

Rev

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

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