Subversion Repositories SmartDukaan

Rev

Rev 13999 | Rev 14001 | 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
 
13582 amit.gupta 161
def getMerchantOrdersByUser(userId, page=1, window=50):
13603 amit.gupta 162
    if page==None:
163
        page = 1
164
 
165
    if window==None:
166
        window = 50
167
    result = {}
13582 amit.gupta 168
    skip = (page-1)*window
13603 amit.gupta 169
    collection = get_mongo_connection().Dtr.merchantOrder
14000 amit.gupta 170
    cursor = collection.find({"userId":userId}).sort("$natural",-1)
13603 amit.gupta 171
    total_count = cursor.count()
172
    pages = total_count/window + (0 if total_count%window==0 else 1)  
173
    print "total_count", total_count
174
    if total_count > skip:
13999 amit.gupta 175
        cursor = cursor.skip(skip).limit(window)
13603 amit.gupta 176
        orders = []
177
        for order in cursor:
178
            del(order["_id"])
179
            orders.append(order)
180
        result['data'] = orders
181
        result['window'] = window
182
        result['totalCount'] = total_count 
183
        result['currCount'] = cursor.count()
184
        result['totalPages'] = pages
185
        result['currPage'] = page    
186
        return result
187
    else:
188
        return result
13630 kshitij.so 189
 
13927 amit.gupta 190
def getRefunds(userId, page=1, window=10):
191
    if page==None:
192
        page = 1
193
 
194
    if window==None:
13995 amit.gupta 195
        window = 10
13927 amit.gupta 196
    result = {}
197
    skip = (page-1)*window
198
    collection = get_mongo_connection().Dtr.refund
199
    cursor = collection.find({"userId":userId})
200
    total_count = cursor.count()
201
    pages = total_count/window + (0 if total_count%window==0 else 1)  
202
    print "total_count", total_count
203
    if total_count > skip:
13991 amit.gupta 204
        cursor = cursor.skip(skip).limit(window).sort([('batchId',-1)])
13927 amit.gupta 205
        refunds = []
206
        for refund in cursor:
207
            del(refund["_id"])
208
            refunds.append(refund)
209
        result['data'] = refunds
210
        result['window'] = window
211
        result['totalCount'] = total_count 
212
        result['currCount'] = cursor.count()
213
        result['totalPages'] = pages
214
        result['currPage'] = page    
215
        return result
216
    else:
217
        return result
218
 
219
def getPendingRefunds(userId):
13991 amit.gupta 220
    print type(userId)
13927 amit.gupta 221
    result = get_mongo_connection().Dtr.merchantOrder\
222
        .aggregate([
223
                    {'$match':{'subOrders.cashBackStatus':Store.CB_APPROVED, 'userId':userId}},
224
                    {'$unwind':"$subOrders"},
225
                    { 
226
                     '$group':{
227
                               '_id':None,
228
                               'amount': { '$sum':'$subOrders.cashBackAmount'},
229
                               }
230
                     }
13987 amit.gupta 231
                ])['result']
232
 
233
    if len(result)>0:
234
        result = result[0]        
235
        result.pop("_id")
236
    else:
237
        result={}
238
        result['amount'] = 0.0
13988 amit.gupta 239
    result['nextCredit'] = datetime.strftime(next_weekday(datetime.now(), 0),"%Y-%m-%d %H:%M:%S")
13927 amit.gupta 240
    return result
13795 kshitij.so 241
def getDeals(category_id, offset, limit, sort, direction):
13922 kshitij.so 242
    if not bool(cashBackMap):
13921 kshitij.so 243
        populateCashBack()
13771 kshitij.so 244
    rank = 1
245
    deals = {}
13910 kshitij.so 246
    outer_query = []
247
    outer_query.append({"showDeal":1})
248
    query = {}
249
    query['$gt'] = 0
250
    outer_query.append({'totalPoints':query})
251
    if category_id in (3,5):
252
        outer_query.append({'category_id':category_id})
13803 kshitij.so 253
    if sort is None or direction is None:
254
        direct = -1
13910 kshitij.so 255
        print outer_query
256
        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 257
    else:
13910 kshitij.so 258
        print outer_query
13803 kshitij.so 259
        direct = direction
13910 kshitij.so 260
        if sort == "bestSellerPoints":
261
            print "yes,sorting by bestSellerPoints"
262
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
263
        else:
264
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 265
    for d in data:
266
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
267
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 268
            item[0]['dealRank'] = rank
269
            try:
270
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
271
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 272
                    item[0]['cash_back_type'] = 0
273
                    item[0]['cash_back'] = 0
13921 kshitij.so 274
                else:
13928 kshitij.so 275
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
276
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 277
            except:
278
                print "Error in adding cashback to deals"
13928 kshitij.so 279
                item[0]['cash_back_type'] = 0
280
                item[0]['cash_back'] = 0
13771 kshitij.so 281
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 282
 
13771 kshitij.so 283
            rank +=1
13785 kshitij.so 284
    return sorted(deals.values(), key=itemgetter('dealRank'))
285
 
286
def getItem(skuId):
13795 kshitij.so 287
    try:
288
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
13785 kshitij.so 289
        return skuData
13795 kshitij.so 290
    except:
291
        return [{}]
13836 kshitij.so 292
 
13921 kshitij.so 293
def __getCashBack(skuId, source_id, category_id):
294
    itemCashBack = itemCashBackMap.get(skuId)
295
    if itemCashBack is not None:
296
        return itemCashBack
297
 
298
    sourceCashBack = cashBackMap.get(source_id)
299
    if sourceCashBack is not None and len(sourceCashBack) > 0:
300
        for cashBack in sourceCashBack:
301
            if cashBack.get(category_id) is None:
302
                continue
303
            else:
304
                return cashBack.get(category_id)
305
    else:
306
        return {}
307
 
13836 kshitij.so 308
def getCashBackDetails(identifier, source_id):
13922 kshitij.so 309
    if not bool(cashBackMap):
13921 kshitij.so 310
        populateCashBack()
311
 
13836 kshitij.so 312
    """Need to add item level cashback, no data available right now."""
13771 kshitij.so 313
 
13921 kshitij.so 314
    if source_id in (1,2,4,5):
13839 kshitij.so 315
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 316
    elif source_id == 3:
13839 kshitij.so 317
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 318
    else:
319
        return {}
13836 kshitij.so 320
    if len(skuData) > 0:
13921 kshitij.so 321
 
322
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
323
        if itemCashBack is not None:
324
            return itemCashBack
325
 
326
        sourceCashBack = cashBackMap.get(source_id)
327
        if sourceCashBack is not None and len(sourceCashBack) > 0:
328
            for cashBack in sourceCashBack:
329
                if cashBack.get(skuData[0]['category_id']) is None:
330
                    continue
331
                else:
332
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 333
        else:
334
            return {} 
335
    else:
336
        return {}
13986 amit.gupta 337
 
338
 
339
def next_weekday(d, weekday):
340
    days_ahead = weekday - d.weekday()
341
    if days_ahead <= 0: # Target day already happened this week
342
        days_ahead += 7
343
    return d + timedelta(days_ahead)
344
 
13771 kshitij.so 345
 
13970 kshitij.so 346
def getAllDealerPrices(offset, limit):
347
    data = []
348
    collection = get_mongo_connection().Catalog.SkuDealerPrices
349
    cursor = collection.find().skip(offset).limit(limit)
350
    for val in cursor:
351
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
352
        if len(master) > 0:
353
            val['brand'] = master['brand']
354
            val['source_product_name'] = master['source_product_name']
355
            val['skuBundleId'] = master['skuBundleId']
356
        else:
357
            val['brand'] = ""
358
            val['source_product_name'] = ""
359
            val['skuBundleId'] = ""
360
        data.append(val)
361
    return data
362
 
363
def addSkuDealerPrice(data):
364
    collection = get_mongo_connection().Catalog.SkuDealerPrices
365
    cursor = collection.find({"sku":data['sku']})
366
    if cursor.count() > 0:
367
        return {0:"Sku information already present."}
368
    else:
369
        collection.insert(data)
370
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
371
        return {1:"Data added successfully"}
372
 
373
def updateSkuDealerPrice(data, _id):
374
    try:
375
        collection = get_mongo_connection().Catalog.SkuDealerPrices
376
        collection.update({'_id':ObjectId(_id)},{"$set":{'dp':data['dp']}},upsert=False, multi = False)
377
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
378
        return {1:"Data updated successfully"}
379
    except:
380
        return {0:"Data not updated."}
381
 
382
def updateExceptionalNlc(data, _id):
383
    try:
384
        collection = get_mongo_connection().Catalog.ExceptionalNlc
385
        collection.update({'_id':ObjectId(_id)},{"$set":{'maxNlc':data['maxNlc'], 'minNlc':data['minNlc'], 'overrideNlc':data['overrideNlc']}},upsert=False, multi = False)
386
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
387
        return {1:"Data updated successfully"}
388
    except:
389
        return {0:"Data not updated."}
390
 
391
 
13572 kshitij.so 392
def main():
13989 amit.gupta 393
    print getPendingRefunds(15) 
13811 kshitij.so 394
 
13921 kshitij.so 395
 
13572 kshitij.so 396
if __name__=='__main__':
13932 amit.gupta 397
    main()