Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
13928 kshitij.so 1
import pymongo
13572 kshitij.so 2
from datetime import datetime
13986 amit.gupta 3
from datetime import timedelta
13927 amit.gupta 4
from dtr.main import Store
13785 kshitij.so 5
from dtr.utils.utils import to_java_date
13970 kshitij.so 6
from operator import itemgetter
7
from bson.objectid import ObjectId
13572 kshitij.so 8
 
9
con = None
13907 kshitij.so 10
cashBackMap = {}
13921 kshitij.so 11
itemCashBackMap = {}
13572 kshitij.so 12
 
13
def get_mongo_connection(host='localhost', port=27017):
14
    global con
15
    if con is None:
16
        print "Establishing connection %s host and port %d" %(host,port)
17
        try:
18
            con = pymongo.MongoClient(host, port)
19
        except Exception, e:
20
            print e
21
            return None
22
    return con
23
 
13907 kshitij.so 24
def populateCashBack():
13921 kshitij.so 25
    print "Populating cashback"
13907 kshitij.so 26
    global cashBackMap
13921 kshitij.so 27
    global itemCashBackMap
28
    cashBackMap = {}
29
    itemCashBackMap = {}
13907 kshitij.so 30
    cashBack = list(get_mongo_connection().Catalog.CategoryCashBack.find())
31
    for row in cashBack:
13970 kshitij.so 32
        temp_map = {}
33
        temp_list = []
13907 kshitij.so 34
        if cashBackMap.has_key(row['source_id']):
35
            arr = cashBackMap.get(row['source_id'])
36
            for val in arr:
37
                temp_list.append(val)
38
            temp_map[row['category_id']] = row
39
            temp_list.append(temp_map)
40
            cashBackMap[row['source_id']] = temp_list 
41
        else:
42
            temp_map[row['category_id']] = row
43
            temp_list.append(temp_map)
44
            cashBackMap[row['source_id']] = temp_list
13921 kshitij.so 45
    itemCashBack = list(get_mongo_connection().Catalog.ItemCashBack.find())
46
    for row in itemCashBack:
47
        if not itemCashBackMap.has_key(row['skuId']):
48
            itemCashBackMap[row['skuId']] = row
13907 kshitij.so 49
 
13572 kshitij.so 50
def addCategoryDiscount(data):
13970 kshitij.so 51
    collection = get_mongo_connection().Catalog.CategoryDiscount
13572 kshitij.so 52
    query = []
53
    data['brand'] = data['brand'].strip().upper()
13970 kshitij.so 54
    data['discountType'] = data['discountType'].upper().strip()
13572 kshitij.so 55
    query.append({"brand":data['brand']})
56
    query.append({"category_id":data['category_id']})
57
    r = collection.find({"$and":query})
58
    if r.count() > 0:
13639 kshitij.so 59
        return {0:"Brand & Category info already present."}
13572 kshitij.so 60
    else:
61
        collection.insert(data)
13970 kshitij.so 62
        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 63
        return {1:"Data added successfully"}
13572 kshitij.so 64
 
13970 kshitij.so 65
def updateCategoryDiscount(data,_id):
66
    try:
67
        collection = get_mongo_connection().Catalog.CategoryDiscount
68
        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)
69
        get_mongo_connection().Catalog.MasterData.update({'brand':data['brand'],'category_id':data['category_id']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
70
        return {1:"Data updated successfully"}
71
    except:
72
        return {0:"Data not updated."}
73
 
74
 
13572 kshitij.so 75
def getAllCategoryDiscount():
76
    data = []
13970 kshitij.so 77
    collection = get_mongo_connection().Catalog.CategoryDiscount
13572 kshitij.so 78
    cursor = collection.find()
79
    for val in cursor:
80
        data.append(val)
81
    return data
82
 
83
def addSchemeDetailsForSku(data):
13970 kshitij.so 84
    collection = get_mongo_connection().Catalog.SkuSchemeDetails
13572 kshitij.so 85
    data['addedOn'] = to_java_date(datetime.now())
86
    collection.insert(data)
13639 kshitij.so 87
    return {1:"Data added successfully"}
13572 kshitij.so 88
 
89
def getAllSkuWiseSchemeDetails():
90
    data = []
13970 kshitij.so 91
    collection = get_mongo_connection().Catalog.SkuSchemeDetails
13572 kshitij.so 92
    cursor = collection.find()
93
    for val in cursor:
94
        data.append(val)
95
    return data
96
 
97
def addSkuDiscountInfo(data):
13970 kshitij.so 98
    collection = get_mongo_connection().Catalog.SkuDiscountInfo
13572 kshitij.so 99
    cursor = collection.find({"sku":data['sku']})
13642 kshitij.so 100
    if cursor.count() > 0:
13639 kshitij.so 101
        return {0:"Sku information already present."}
13572 kshitij.so 102
    else:
103
        collection.insert(data)
13970 kshitij.so 104
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
13639 kshitij.so 105
        return {1:"Data added successfully"}
13572 kshitij.so 106
 
13970 kshitij.so 107
def getallSkuDiscountInfo(offset, limit):
13572 kshitij.so 108
    data = []
13970 kshitij.so 109
    collection = get_mongo_connection().Catalog.SkuDiscountInfo
110
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 111
    for val in cursor:
13970 kshitij.so 112
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
113
        if len(master) > 0:
114
            val['brand'] = master['brand']
115
            val['source_product_name'] = master['source_product_name']
116
            val['skuBundleId'] = master['skuBundleId']
117
        else:
118
            val['brand'] = ""
119
            val['source_product_name'] = ""
120
            val['skuBundleId'] = ""
13572 kshitij.so 121
        data.append(val)
122
    return data
123
 
13970 kshitij.so 124
def updateSkuDiscount(data,_id):
125
    try:
126
        collection = get_mongo_connection().Catalog.SkuDiscountInfo
127
        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)
128
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
129
        return {1:"Data updated successfully"}
130
    except:
131
        return {0:"Data not updated."}
132
 
133
 
13572 kshitij.so 134
def addExceptionalNlc(data):
13970 kshitij.so 135
    collection = get_mongo_connection().Catalog.ExceptionalNlc
13572 kshitij.so 136
    cursor = collection.find({"sku":data['sku']})
13642 kshitij.so 137
    if cursor.count() > 0:
13639 kshitij.so 138
        return {0:"Sku information already present."}
13572 kshitij.so 139
    else:
140
        collection.insert(data)
13970 kshitij.so 141
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
13639 kshitij.so 142
        return {1:"Data added successfully"}
13572 kshitij.so 143
 
13970 kshitij.so 144
def getAllExceptionlNlcItems(offset, limit):
13572 kshitij.so 145
    data = []
13970 kshitij.so 146
    collection = get_mongo_connection().Catalog.ExceptionalNlc
13572 kshitij.so 147
    cursor = collection.find()
148
    for val in cursor:
13970 kshitij.so 149
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
150
        if len(master) > 0:
151
            val['brand'] = master['brand']
152
            val['source_product_name'] = master['source_product_name']
153
            val['skuBundleId'] = master['skuBundleId']
154
        else:
155
            val['brand'] = ""
156
            val['source_product_name'] = ""
157
            val['skuBundleId'] = ""
13572 kshitij.so 158
        data.append(val)
159
    return data
160
 
14005 amit.gupta 161
def getMerchantOrdersByUser(userId, page=1, window=50, searchMap={}):
162
    if searchMap is None:
163
        searchMap = {}
13603 amit.gupta 164
    if page==None:
165
        page = 1
166
 
167
    if window==None:
168
        window = 50
169
    result = {}
13582 amit.gupta 170
    skip = (page-1)*window
14005 amit.gupta 171
 
172
    searchMap['userId'] = userId
13603 amit.gupta 173
    collection = get_mongo_connection().Dtr.merchantOrder
14005 amit.gupta 174
    cursor = collection.find(searchMap).sort("_id",-1)
13603 amit.gupta 175
    total_count = cursor.count()
176
    pages = total_count/window + (0 if total_count%window==0 else 1)  
177
    print "total_count", total_count
178
    if total_count > skip:
13999 amit.gupta 179
        cursor = cursor.skip(skip).limit(window)
13603 amit.gupta 180
        orders = []
181
        for order in cursor:
14002 amit.gupta 182
            del(order["_id"])
183
            orders.append(order)
13603 amit.gupta 184
        result['data'] = orders
185
        result['window'] = window
186
        result['totalCount'] = total_count 
187
        result['currCount'] = cursor.count()
188
        result['totalPages'] = pages
189
        result['currPage'] = page    
190
        return result
191
    else:
192
        return result
13630 kshitij.so 193
 
13927 amit.gupta 194
def getRefunds(userId, page=1, window=10):
195
    if page==None:
196
        page = 1
197
 
198
    if window==None:
13995 amit.gupta 199
        window = 10
13927 amit.gupta 200
    result = {}
201
    skip = (page-1)*window
202
    collection = get_mongo_connection().Dtr.refund
203
    cursor = collection.find({"userId":userId})
204
    total_count = cursor.count()
205
    pages = total_count/window + (0 if total_count%window==0 else 1)  
206
    print "total_count", total_count
207
    if total_count > skip:
13991 amit.gupta 208
        cursor = cursor.skip(skip).limit(window).sort([('batchId',-1)])
13927 amit.gupta 209
        refunds = []
210
        for refund in cursor:
211
            del(refund["_id"])
212
            refunds.append(refund)
213
        result['data'] = refunds
214
        result['window'] = window
215
        result['totalCount'] = total_count 
216
        result['currCount'] = cursor.count()
217
        result['totalPages'] = pages
218
        result['currPage'] = page    
219
        return result
220
    else:
221
        return result
222
 
223
def getPendingRefunds(userId):
13991 amit.gupta 224
    print type(userId)
13927 amit.gupta 225
    result = get_mongo_connection().Dtr.merchantOrder\
226
        .aggregate([
227
                    {'$match':{'subOrders.cashBackStatus':Store.CB_APPROVED, 'userId':userId}},
228
                    {'$unwind':"$subOrders"},
229
                    { 
230
                     '$group':{
231
                               '_id':None,
232
                               'amount': { '$sum':'$subOrders.cashBackAmount'},
233
                               }
234
                     }
13987 amit.gupta 235
                ])['result']
236
 
237
    if len(result)>0:
238
        result = result[0]        
239
        result.pop("_id")
240
    else:
241
        result={}
242
        result['amount'] = 0.0
13988 amit.gupta 243
    result['nextCredit'] = datetime.strftime(next_weekday(datetime.now(), 0),"%Y-%m-%d %H:%M:%S")
13927 amit.gupta 244
    return result
13795 kshitij.so 245
def getDeals(category_id, offset, limit, sort, direction):
13922 kshitij.so 246
    if not bool(cashBackMap):
13921 kshitij.so 247
        populateCashBack()
13771 kshitij.so 248
    rank = 1
249
    deals = {}
13910 kshitij.so 250
    outer_query = []
251
    outer_query.append({"showDeal":1})
252
    query = {}
253
    query['$gt'] = 0
254
    outer_query.append({'totalPoints':query})
255
    if category_id in (3,5):
256
        outer_query.append({'category_id':category_id})
13803 kshitij.so 257
    if sort is None or direction is None:
258
        direct = -1
13910 kshitij.so 259
        print outer_query
260
        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 261
    else:
13910 kshitij.so 262
        print outer_query
13803 kshitij.so 263
        direct = direction
13910 kshitij.so 264
        if sort == "bestSellerPoints":
265
            print "yes,sorting by bestSellerPoints"
266
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
267
        else:
268
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 269
    for d in data:
270
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
271
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 272
            item[0]['dealRank'] = rank
273
            try:
274
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
275
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 276
                    item[0]['cash_back_type'] = 0
277
                    item[0]['cash_back'] = 0
13921 kshitij.so 278
                else:
13928 kshitij.so 279
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
280
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 281
            except:
282
                print "Error in adding cashback to deals"
13928 kshitij.so 283
                item[0]['cash_back_type'] = 0
284
                item[0]['cash_back'] = 0
13771 kshitij.so 285
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 286
 
13771 kshitij.so 287
            rank +=1
13785 kshitij.so 288
    return sorted(deals.values(), key=itemgetter('dealRank'))
289
 
290
def getItem(skuId):
13795 kshitij.so 291
    try:
292
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
13785 kshitij.so 293
        return skuData
13795 kshitij.so 294
    except:
295
        return [{}]
13836 kshitij.so 296
 
13921 kshitij.so 297
def __getCashBack(skuId, source_id, category_id):
298
    itemCashBack = itemCashBackMap.get(skuId)
299
    if itemCashBack is not None:
300
        return itemCashBack
301
 
302
    sourceCashBack = cashBackMap.get(source_id)
303
    if sourceCashBack is not None and len(sourceCashBack) > 0:
304
        for cashBack in sourceCashBack:
305
            if cashBack.get(category_id) is None:
306
                continue
307
            else:
308
                return cashBack.get(category_id)
309
    else:
310
        return {}
311
 
13836 kshitij.so 312
def getCashBackDetails(identifier, source_id):
13922 kshitij.so 313
    if not bool(cashBackMap):
13921 kshitij.so 314
        populateCashBack()
315
 
13836 kshitij.so 316
    """Need to add item level cashback, no data available right now."""
13771 kshitij.so 317
 
13921 kshitij.so 318
    if source_id in (1,2,4,5):
13839 kshitij.so 319
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 320
    elif source_id == 3:
13839 kshitij.so 321
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 322
    else:
323
        return {}
13836 kshitij.so 324
    if len(skuData) > 0:
13921 kshitij.so 325
 
326
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
327
        if itemCashBack is not None:
328
            return itemCashBack
329
 
330
        sourceCashBack = cashBackMap.get(source_id)
331
        if sourceCashBack is not None and len(sourceCashBack) > 0:
332
            for cashBack in sourceCashBack:
333
                if cashBack.get(skuData[0]['category_id']) is None:
334
                    continue
335
                else:
336
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 337
        else:
338
            return {} 
339
    else:
340
        return {}
13986 amit.gupta 341
 
342
 
343
def next_weekday(d, weekday):
344
    days_ahead = weekday - d.weekday()
345
    if days_ahead <= 0: # Target day already happened this week
346
        days_ahead += 7
347
    return d + timedelta(days_ahead)
348
 
13771 kshitij.so 349
 
13970 kshitij.so 350
def getAllDealerPrices(offset, limit):
351
    data = []
352
    collection = get_mongo_connection().Catalog.SkuDealerPrices
353
    cursor = collection.find().skip(offset).limit(limit)
354
    for val in cursor:
355
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
356
        if len(master) > 0:
357
            val['brand'] = master['brand']
358
            val['source_product_name'] = master['source_product_name']
359
            val['skuBundleId'] = master['skuBundleId']
360
        else:
361
            val['brand'] = ""
362
            val['source_product_name'] = ""
363
            val['skuBundleId'] = ""
364
        data.append(val)
365
    return data
366
 
367
def addSkuDealerPrice(data):
368
    collection = get_mongo_connection().Catalog.SkuDealerPrices
369
    cursor = collection.find({"sku":data['sku']})
370
    if cursor.count() > 0:
371
        return {0:"Sku information already present."}
372
    else:
373
        collection.insert(data)
374
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
375
        return {1:"Data added successfully"}
376
 
377
def updateSkuDealerPrice(data, _id):
378
    try:
379
        collection = get_mongo_connection().Catalog.SkuDealerPrices
380
        collection.update({'_id':ObjectId(_id)},{"$set":{'dp':data['dp']}},upsert=False, multi = False)
381
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
382
        return {1:"Data updated successfully"}
383
    except:
384
        return {0:"Data not updated."}
385
 
386
def updateExceptionalNlc(data, _id):
387
    try:
388
        collection = get_mongo_connection().Catalog.ExceptionalNlc
389
        collection.update({'_id':ObjectId(_id)},{"$set":{'maxNlc':data['maxNlc'], 'minNlc':data['minNlc'], 'overrideNlc':data['overrideNlc']}},upsert=False, multi = False)
390
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
391
        return {1:"Data updated successfully"}
392
    except:
393
        return {0:"Data not updated."}
394
 
395
 
13572 kshitij.so 396
def main():
13989 amit.gupta 397
    print getPendingRefunds(15) 
13811 kshitij.so 398
 
13921 kshitij.so 399
 
13572 kshitij.so 400
if __name__=='__main__':
13932 amit.gupta 401
    main()