Subversion Repositories SmartDukaan

Rev

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